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
?
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 }
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With