问题描述
我可以按如下方式分配元组:
I can assign a tuple as follows:
var (min, max) = (1, 2)
但我不能按如下方式重新分配
(min, max) = (1, 3) //compiler error: ';' expected but '=' found
相反,我似乎必须这样做:
Instead I seem to have to do:
min = 1
max = 3
为什么后者有效而前者无效?
Why does the latter work whereas the former does not?
推荐答案
好吧,我想是因为它是那样指定的.
Well, because it was spec'ed that way, I suppose.
这个,元组分配,是模式匹配的一个例子.模式匹配发生在我记得的三个地方:
This, the tuple assignment, is an example of pattern matching. Pattern matching happens in three places that I recall of:
var PATTERN = ... // or val
for (PATTERN <- ...) ...
case PATTERN => ...
所以所有这些情况都有效:
So all these cases work:
val l = List((1,'a'), (2,'b'), (3,'c'))
var (n, c) = l(0)
for ((n, c) <- l) println(n+": "+c)
l(1) match {
case (n, c) => println(n+": "+c)
}
现在,以最后一个例子为例,使用 case
的例子.请注意,该示例中的 n
和 c
不是相同的 n
和 c
定义得早一点.模式匹配会为新标识符n
和c
赋值,这将影响case 语句.同样的事情发生在
for
示例中,它没有改变之前定义的 n
和 c
.
Now, take the last example, the one using
case
. Note that n
and c
in that example are not the same n
and c
defined a bit earlier. The pattern match will assign values to new identifiers n
and c
, which will shadow the previous definition for the escope of the case
statement. The same thing happened on the for
example, which did not change n
and c
previously defined.
现在,您想要发生的是覆盖以前的值,而不是为新标识符分配新值.这不是模式匹配的工作方式,这意味着实现它需要一个全新的规则.由于 Scala 温和地促使人们走向不变性,我认为他们没有创建新规则来处理这个问题并不是没有道理的.
Now, what you want to happen is to overwrite the previous value, instead of assign new values to new identifiers. That's not how pattern matching works, which means making it happen would entail an entirely new rule. Since Scala gently prods people towards immutability, I suppose it's not unreasonable they did not create a new rule just to handle this.
这篇关于元组参数声明和赋值奇怪的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!