Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
945 views
in Technique[技术] by (71.8m points)

syntax - 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

(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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
...