tags:

views:

207

answers:

2

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?

+1  A: 

Scala has 2 types of variables: vals and vars. Vals are similar to Java's final variables, so as far as I understand from what you're asking, the only way to assign new values in parallel to vals is by:

scala> val (x, y) = (1, 2);

or

scala> val s = (3, 4);
s: (Int, Int) = (3,4)

scala> s._1
res1: Int = 3

scala> s._2
res2: Int = 4
hyperboreean
I understand why you can't assign a new value to a val. I am talking about parallel assignment of vars. In the code from my question, x and y are both vars.
dbyrne
He's asking if you can do `val (x,y) = (1,2)` and `var (x,y) = (1,2)` then why can't you do `var x; var y; (x,y) = (1,2)`?
Ken Bloom
+7  A: 

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.

Michel Krämer