Scala Tuple Deconstruction

scala

Solution

Unfortunately, you cannot do multiple assignments in Scala. But you may use tuples, if they fit your problem:

scala> var xy = (1,2)
xy: (Int, Int) = (1,2)

scala> xy = (xy._1 + xy._2, xy._2 - xy._1)
xy: (Int, Int) = (3,1)

This way, `xy` is one tuple with two values. The first value can be accessed using `xy._1`, the second one using `xy._2`.

Problem

I am new to Scala, and ran across a small hiccup that has been annoying me. Initializing two vars in parallel works great: `var (x,y) = (1,2)` However I can't find a way to assign new values in parallel: `(x,y) = (x+y,y-x) //invalid syntax` I end up writing something like this: `val xtmp = x+y; y = x-y; x = xtmp` I realize writing functional code is one way of avoiding this, but there are certain situations where vars just make more sense. I have two questions: 1) Is there a better way of doing this? Am I missing something? 2) What is the reason for not allowing true parallel assignment?

Original source