Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scala Tuple Deconstruction

Tags:

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?

like image 524
dbyrne Avatar asked May 05 '10 20:05

dbyrne


People also ask

Is tuple immutable in Scala?

In Scala, a tuple is a value that contains a fixed number of elements, each with its own type. Tuples are immutable.

Can we have variables of different types inside of a tuple in Scala?

Thankfully, Scala already has a built-in tuple type, which is an immutable data structure that we can use for holding up to 22 elements with different types.


2 Answers

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.

like image 153
Michel Krämer Avatar answered Dec 22 '22 00:12

Michel Krämer


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 
like image 21
hyperboreean Avatar answered Dec 22 '22 00:12

hyperboreean