简体   繁体   English

Scala-“ val a = b = c”的赋值关联性

[英]Scala - the assignment associativity of “val a = b = c”

As I read from book, scala operator associativity comes from left to right except operator ends with ":" char. 正如我从书中读到的那样,scala运算符的关联性是从左到右,除了运算符以“:” char结尾。

Given the val a = b = c , it becomes val a = (b = c) and makes a is initialized as Unit. 给定val a = b = c ,它将变为val a = (b = c)并使a初始化为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 ? 但是为什么它不变为(val a = b) = c ,并且由于使用Unit(从a=b返回)来接收c而导致编译错误?

And after I really types (val a = b) = c , the compiler complains illeagal start of simple expression and pointers to val . 在我真正键入(val a = b) = c ,编译器抱怨illeagal start of simple expressionval指针的illeagal start of simple expression Why are these two assignment operators not grouped from left to right? 为什么这两个赋值运算符没有从左到右分组?

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. 这里要注意的重要一点是val a = b = c是声明而不是表达式,但是优先级和关联性是适用于表达式的概念。

Looking at the Scala 2.11 Language Specification, 4.1 Value Declarations and Definitions , you can see that 查看Scala 2.11语言规范,4.1值声明和定义 ,您会看到

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): 是一个基本宣告落入PatVarDef情况下,因此它可以被理解为(简化Pattern2部分的具体情况varid这里):

'val' varid '=' Expr

Thus, here we have 因此,这里有

  • the variable identifier varid is a , 变量标识符varida
  • the expression Expr is b = c , 表达式Exprb = c
  • a is assigned the value b = c evaluates to, which happens to be Unit . a赋值b = c求和,恰好是Unit

For the later see What is the motivation for Scala assignment evaluating to Unit rather than the value assigned? 对于后面的内容,请参见将Scala赋值给Unit而不是赋值的动机是什么?

Note that the above assumes that b is a var , eg, 请注意,以上假设bvar ,例如,

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 ). 因为b在第三行中被重新分配(否则,您将得到error: reassignment to val )。 If you want to assign the same value to two val for some reason, you can use 如果出于某种原因要为两个val分配相同的值,可以使用

val c = 17
val a, b = c

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM