1

As I read from book, scala operator associativity comes from left to right except operator ends with ":" char.

Given the val a = b = c, it becomes val a = (b = c) and makes a is initialized as Unit.

But why does not it become (val a = b) = c, and it cause that compile error because to use a Unit(returned from a=b) to receive c?

And after I really types (val a = b) = c, the compiler complains illeagal start of simple expression and pointers to val. Why are these two assignment operators not grouped from left to right?

Chen OT
  • 3,486
  • 2
  • 24
  • 46

1 Answers1

2

The important thing to see here is that val a = b = c is a declaration and not an expression, but precedence and associativity are notions applying to expressions.

Looking at the Scala 2.11 Language Specification, 4.1 Value Declarations and Definitions, you can see that

val a = b = c

is a basic declaration falling into the PatVarDef case, so it can be read as (simplifying the Pattern2 part to the specific case of varid here):

'val' varid '=' Expr

Thus, here we have

  • the variable identifier varid is a,
  • the expression Expr is b = c,
  • a is assigned the value b = c evaluates to, which happens to be Unit.

For the later see What is the motivation for Scala assignment evaluating to Unit rather than the value assigned?

Note that the above assumes that b is a var, e.g.,

val c = 17
var b = 3
val a = b = c

as b is reassigned in the third line (else you would get error: reassignment to val). If you want to assign the same value to two val for some reason, you can use

val c = 17
val a, b = c
Community
  • 1
  • 1
godfatherofpolka
  • 1,645
  • 1
  • 11
  • 24
  • "> Evaluation of the value definition implies evaluation of its right-hand side e" It looks like it resolves the `value definition`("val a = E") first then evaluates the right-hand side of `expression E` ("b = c"), then assign the `result of E to a`. Thanks – Chen OT May 06 '15 at 16:38
  • on my system 2.11.6, if they are vals it croaks, vars ok for b and c, or b at least, cuz it wants to set b to value of c. a is left as (). It's gonna stomp on b. – Drew May 06 '15 at 16:44