简体   繁体   中英

In Scala, is assignment operator “=” a method call?

As per Scala book, "Programming In Scala" -

Scala is an object-oriented language in pure form: every value is an object and every operation is a method call. For example, when you say 1 + 2 in Scala, you are actually invoking a method named + defined in class Int.

In that sense, what about assignment operation using "=" operator? Is that also a method? Seems unlikely, because then it has to be present in all classes or some common super class (say, java.lang.Object ?) that all classes have to inherit it from. Or is it that not all operations are really method calls in Scala?

A little addition to Jatin answer. There is one case when = can be considered as a method call, but actually it's just a syntactic sugar. In OO part of Scala, where ugly var s lives, you can write the following:

class Test { 
  private var x0: Int = 0
  def x = x0
  def x_=(a: Int) = x0 = a 
}

Then you can assign new ints to x :

scala> val t = new Test
t: Test = Test@4166d6d3

scala> t.x = 1
t.x: Int = 1

The last line will be desugared into t.x_=(1) . I think in this case, considering syntactic sugar, it's possible to say that = is a method call.

Nope. Assignment operator ( = ) is a reserved word. Also the below are:

_ : = => <- <: <% >: # @

For a more comprehensive list refer § 1.1 . Some more information regarding = is described in § 6.12.4 .

So yes it is not a method call.

尽管其他答案对于标准Scala都是正确的,但还有一个称为Scala-Virtualized的变体,其中=和其他控件结构方法调用。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM