Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In Scala, is assignment operator "=" a method call?

Tags:

scala

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?

like image 386
Sumit Nigam Avatar asked Sep 30 '13 05:09

Sumit Nigam


People also ask

What type of operator is assignment operator?

There are two kinds of assignment operations: simple assignment, in which the value of the second operand is stored in the object specified by the first operand. compound assignment, in which an arithmetic, shift, or bitwise operation is performed before storing the result.

Is called as assignment operator?

An assignment operator is the operator used to assign a new value to a variable, property, event or indexer element in C# programming language. Assignment operators can also be used for logical operations such as bitwise logical operations or operations on integral operands and Boolean operands.

What do you mean by assignment operator?

The assignment operator = assigns the value of its right-hand operand to a variable, a property, or an indexer element given by its left-hand operand. The result of an assignment expression is the value assigned to the left-hand operand.


2 Answers

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 vars 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.

like image 142
4lex1v Avatar answered Sep 19 '22 20:09

4lex1v


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.

like image 31
Jatin Avatar answered Sep 18 '22 20:09

Jatin