2

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

1 Answer 1

3

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.

Sign up to request clarification or add additional context in comments.

4 Comments

I am doing some tradtional CS algorithms and these tend to use var's more frequently than general scala code. In this case updating var's would have been nice to have.
You can convert many traditional algorithms to functional code by replacing while loops with recursive calls.
Yea but let's just say that recursive calls are not the easiest things to do under time pressure - and they're often pretty not readable. I am not a pure functional programmer and have no interest in being one. I am mostly forced into python on my ML/AI job so it is impractical to write code that I find mildly challenging and others on the team would have no chance of getting. Also can be more inefficient
Porting imperative algorithms to functional Scala under time pressure is never going to be easy, especially if you are not comfortable with recursive code. So I would stick with the imperative version and either make the var a tuple or add the extra lines of code needed to copy the return values from the tuple into separate vars.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.