I can do something like
def f(): Tuple2[String, Long] = ...
val (a, b) = f()
What about if the variables are already existing? I'm running the same sets of data over filters and I don't want to chain them (long names and such). This is what I tried, but it complains about expecting ; instead of = on the last line:
var a = ...initialization for this data
var b = ...some other init
(a, b) = g(a, b) // error: expected ';' but found '='
Is there a way to avoid an intermediary tuple?
As Alex pointed out, the short answer is no. What's going on with your code is this: when a and b are already bound variables in the current scope, (a, b) means "take the values of a and b and construct a tuple from them."
Therefore,
(a, b) = ...
is equivalent to
(new Tuple2(a, b)) = ...
which is obviously not what you want (besides being nonsensical).
The syntax you want (ability to assign to multiple variables at once) simply doesn't exist. You can't even assign the same value to multiple preexisting variables at once (the usual syntax "a = b = ..." that's found in many other languages doesn't work in Scala.) I don't think it's an accident that vals get preferential treatment over vars; they're almost always a better idea.
It sounds like all of this is taking place inside of a loop of some kind, and doing repeated assignments. This is not very idiomatic Scala. I would recommend that you try to eliminate the usage of vars in your program and do things in a more functional way, using the likes of map, flatMap, filter, foldLeft, etc.
Short answer: No.
It works for new values because that syntax is treated as a pattern matching, just like case statements. So, as Alex said, you cannot do it.
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