views:

159

answers:

2

When this code is executed:

var a = 24
var b = Array (1, 2, 3)
a = 42
b = Array (3, 4, 5)
b (1) = 42

I see three (five?) assignments here. What is the name of the method call that is called in such circumstances? Is it operator overloading?

Update:
Can I create a class and overload assignment? ( x = y not x(1) = y )

+5  A: 

Having this file:

//assignmethod.scala
object Main {
  def main(args: Array[String]) {
    var a = 24
    var b = Array (1, 2, 3)
    a = 42
    b = Array (3, 4, 5)
    b (1) = 42
  }
}

running scalac -print assignmethod.scala gives us:

[[syntax trees at end of cleanup]]// Scala source: assignmethod.scala
package <empty> {
  final class Main extends java.lang.Object with ScalaObject {
    def main(args: Array[java.lang.String]): Unit = {
      var a: Int = 24;
      var b: Array[Int] = scala.Array.apply(1, scala.this.Predef.wrapIntArray(Array[Int]{2, 3}));
      a = 42;
      b = scala.Array.apply(3, scala.this.Predef.wrapIntArray(Array[Int]{4, 5}));
      b.update(1, 42)
    };
    def this(): object Main = {
      Main.super.this();
      ()
    }
  }
}

As you can see the compiler just changes the last one (b (1) = 42) to the method call:

b.update(1, 42)
michael.kebe
Thank you. Very useful answer.
Łukasz Lew
+2  A: 

Complementing Michael's answer, assignment can't be overridden in Scala, though you can create an assignment-like operator, like :=, for exmaple.

The "assignments" that can be overridden are:

// method update
a(x) = y 
// method x_=, assuming method x exists and is also visible 
a.x = y
// method +=, though it will be converted to x = x + y if method += doesn't exist
a += y
Daniel