开发者

Tuple parameter declaration and assignment oddity

I can assign a tuple as follows:

var (min, max) = (1, 2)

But I cannot then re-assign as follows

(mi开发者_运维百科n, 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)
}

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.

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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜