Scala parallel assignments only in declarations

2020-07-13 10:49发布

问题:

Having:

def f () = {
    (1, "two", 3.0)
}

Why is it ok

var (x, y, z) = f()

but not


var i = 0
var j = "hello"
var k = 0.0

// use i, j, k
...
//then
(i, j, k) = f() // ; expected but = found

?

回答1:

You see here a limited version of pattern matching when initializing variables. Note that this works not only for tuples:

val a :: b = List(1,2,3)
println(a) //1
println(b) //List(2, 3)

This feature seems to be borrowed directly from Haskell, where you can use patterns for initialization as well:

let (a,b) = getTuple 
in a*b

As Haskell has no mutable data, there is no way to assign something.

In Scala you could do something like this, but I guess this was considered too confusing, or maybe too difficult to implement. You can always use a match expression as usual, and often you need just a case, e.g. List((1,2),(3,4)).map{ case (a,b) => a*b }.



回答2:

My suspicion would be that without the "var" or "val" to the left of the tuple of variable names, the compiler treats the tuple as a tuple. That is, you're really trying to assign a value to an instance of Tuple3 and not to the three variables, and that makes no sense to the compiler.

Incidentally, using a function and various datatypes in your example isn't relevant. Here's a simpler example:

scala> var ( i, j, k ) = ( 1, 2, 3 )
i: Int = 1
j: Int = 2
k: Int = 3

scala> ( i, j, k ) = ( 4, 5, 6 )
<console>:1: error: ';' expected but '=' found.
       ( i, j, k ) = ( 4, 5, 6 )
                   ^