Scala中的多个常量赋值

时间:2016-09-10 11:56:55

标签: scala variable-assignment

我知道为什么我可以使用元组分配多个变量,而不是多个常量?

scala> val (myVar1, myVar2) = (1, 2)
myVar1: Int = 1
myVar2: Int = 2

scala> val (MyConst1, MyConst2) = (1, 2)
<console>:7: error: not found: value MyConst1
       val (MyConst1, MyConst2) = (1, 2)
            ^
<console>:7: error: not found: value MyConst2
       val (MyConst1, MyConst2) = (1, 2)
                      ^

我认为实际上这仅仅是命名约定的问题,但这看起来像Scala以不同的上/下首字母对待标识符。

2 个答案:

答案 0 :(得分:1)

正如Samar建议的那样,在他的评论中,由于您声明了多个变量,因此涉及模式匹配,并且这些大写标识符实际上被视为类,正如您的REPL错误所示,它们无法找到。

scala> var (Const1, Const2) = (1, 2)
<console>:7: error: not found: value Const1    // <- Const1 class not found
       var (Const1, Const2) = (1, 2)
            ^
<console>:7: error: not found: value Const2   // <- Const2 class not found
       var (Const1, Const2) = (1, 2)    
                    ^

scala> var (const1, const2) = (1, 2)   // <- const1, const2 not treated as classes in this case
const1: Int = 1
const2: Int = 2

答案 1 :(得分:1)

Pattern matching section提及varid(例如Simple Pattern)。现在syntax summary varid定义为

lower            ::=  ‘a’ | … | ‘z’ // and Unicode category Ll
...
varid            ::=  lower idrest