Scala parallel assignments only in declarations

こ雲淡風輕ζ 提交于 2019-12-06 02:12:09

问题


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 )
                   ^


来源:https://stackoverflow.com/questions/5747783/scala-parallel-assignments-only-in-declarations

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!