Tuple parameter declaration and assignment oddity

后端 未结 1 1831
眼角桃花
眼角桃花 2020-11-29 06:51

I can assign a tuple as follows:

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

But I cannot then re-assign as follows

(min, max) = (1, 3         


        
相关标签:
1条回答
  • 2020-11-29 07:18

    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 讨论(0)
提交回复
热议问题