Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Assign method in Scala

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 )

like image 206
Łukasz Lew Avatar asked Nov 28 '22 04:11

Łukasz Lew


1 Answers

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)
like image 137
michael.kebe Avatar answered Dec 05 '22 03:12

michael.kebe