Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scala parallel assignments only in declarations

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

?

like image 803
cibercitizen1 Avatar asked Apr 21 '11 17:04

cibercitizen1


1 Answers

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 }.

like image 109
Landei Avatar answered Sep 23 '22 05:09

Landei