Assign Method to 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 here three (five?) Tasks. What is the method call called in such circumstances? Is the operator overloaded?

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

+4
source share
2 answers

The presence of 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 simply changes the last ( b (1) = 42 ) to a method call:

 b.update(1, 42) 
+16
source

In addition to Michael's answer, the assignment cannot be overridden in Scala, although you can create, for example, an assignment type statement, for example := .

The "assignments" that can be redefined are as follows:

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

Source: https://habr.com/ru/post/1309405/


All Articles