Reputation: 710
Assume I have a function that return multiple values in scala.
def foo:(Double, Double) = {
(1.1, 2.2)
}
I can call it as below without a problem.
val bar = foo
or
val (x, y) = foo
However, if I try to update existing variables like below, it doesn't work.
var x = 1.0
var y = 2.0
(x, y) = foo
This returns an error saying error: ';' expected but '=' found
Is there any reason behind this. Why can't I update the existing variables using (x, y) = foo
Upvotes: 2
Views: 512
Reputation: 27356
The syntax for multiple assignment is actually an example of pattern matching. So this
val (x, y) = foo
...
is sort of equivalent to
foo match {
case (x, y) =>
...
This means that you can use more advanced pattern matching syntax like this:
val f @ (x, y) = foo
or this
val (x, _) = foo
But pattern matching can only be used to extract values into new variables, it can't be used to update existing variables, which is why the last bit of code does not compile. Scala code tends to avoid var
anyway, so this is not a major problem for most programs.
Upvotes: 3