Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

The method execution puzzle in Scala

First I declare a class:

class Op(var x : Int) {
  def +++(op: Op) = {
    println(this.x + " +++ " + op.x)
    this.x += op.x
    this
  } 
  def ***(op: Op) = {
    println(this.x + " *** " + op.x)
    this.x *= op.x
    this
  }
}

Now I execute the expression in REPL:

op1 +++ op2 +++ op3 *** op4

and it outputs

enter image description here

But why doesn't the method *** go first? Isn't the priority of *** higher than +++? And how about Java and C? Is it the same as in Scala?

like image 603
爱国者 Avatar asked Nov 25 '11 08:11

爱国者


1 Answers

op1 +++ op2 +++ op3 *** op4

is equivalent to

((op1 +++ op2) +++ (op3 *** op4))

since method calls are left-associative. Thus first (op1 +++ op2) is evaluated, since it's the first operand to the second +++. Then the second operand, (op3 *** op4) is evaluated. And finally, the outermost operator is evaluated.

The same would be true for op1 + op2 + op3 * op4 in C or Java.

like image 199
Kim Stebel Avatar answered Sep 28 '22 02:09

Kim Stebel