加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

= Scala中的运算符

发布时间:2020-12-16 18:18:59 所属栏目:安全 来源:网络整理
导读:我正在阅读M. Odersky的 Scala编程,现在我正在努力理解运算符的含义.据我所知,Scala中的任何运算符都只是一种方法.请考虑以下示例: class OperatorTest(var a : Int) { def +(ot: OperatorTest): OperatorTest = { val retVal = OperatorTest(0); retVal.a
我正在阅读M. Odersky的 Scala编程,现在我正在努力理解运算符的含义.据我所知,Scala中的任何运算符都只是一种方法.请考虑以下示例:

class OperatorTest(var a : Int) {

  def +(ot: OperatorTest): OperatorTest = {
    val retVal = OperatorTest(0);
    retVal.a = a + ot.a;
    println("=")
    return retVal;
  }
}

object OperatorTest {
  def apply(a: Int) = new OperatorTest(a);
}

在这种情况下,我们只在此类中定义了运算符.如果我们键入这样的东西:

var ot = OperatorTest(10);
var ot2 = OperatorTest(20);
ot += ot2;
println(ot.a);

然后

=+
30

将是输出.所以我假设对于Scala中的每个类(或类型?),我们为它定义了=运算符,a = b iff a = a b.但是因为每个运算符只是一个方法,其中=运算符定义了?也许有一些类(如Java中的Object)包含这些运算符的所有defenition等等.

我看着AnyRef希望找到,但不能.

解决方法

=和类似的运算符被编译器去掉,以防定义了no =. (同样适用于其他操作符.)检查Scala语言规范( 6.12.4):

Assignment operators are treated specially in that they can be
expanded to assignments if no other interpretation is valid.

Let’s consider an assignment operator such as += in an infix operation
l += r,where l,r are expressions. This operation can be
re-interpreted as an operation which corresponds to the assignment

l = l + r except that the operation’s left-hand-side l is evaluated
only once.

The re-interpretation occurs if the following two conditions are
fulfilled.

The left-hand-side l does not have a member named +=,and also cannot be converted by an implicit conversion to a value with a member named +=. The assignment l = l + r is type-correct. In particular this implies that l refers to a variable or object that can be assigned to,and that is convertible to a value with a member named +.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读