Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swapping two vars in scala [duplicate]

Possible Duplicate:
Tuple parameter declaration and assignment oddity

In python I can do

>>> (a,b) = (1,2)
>>> (b,a) = (a,b)
>>> (a,b)
(2, 1)

But in scala:

Welcome to Scala version 2.8.1.final (OpenJDK Server VM, Java 1.6.0_20).
Type in expressions to have them evaluated.
Type :help for more information.

scala> var (a,b) = (1,2)
a: Int = 1
b: Int = 2

scala> (a,b)=(b,a)
<console>:1: error: ';' expected but '=' found.
       (a,b)=(b,a)
            ^

So while I can initialise vars as a tuple, I cannot assign them as a tuple. Any way to get around this, other than using a tmp var?

like image 679
georg Avatar asked Jul 10 '11 15:07

georg


2 Answers

This is Scala 2.9.0.1

scala> val pair = (1,2)
pair: (Int,Int) = (1,2)

scala> val swappedPair = pair.swap
swappedPair: (Int,Int) = (2,1)

The method swap produces another tuple instead of changing the old one and I don't know if it has been there in Scala 2.8.1.

like image 169
agilesteel Avatar answered Sep 20 '22 22:09

agilesteel


Unfortunately, there's no simple way. The expression (a,b) constructs an immutable object of type Tuple[Int, Int]. Within this tuple, the identities of a and b as mutable vars are lost. Two previous questions may give a little more information:

Tuple parameter declaration and assignment oddity

Is it possible to have tuple assignment to variables in Scala?

like image 31
Kipton Barros Avatar answered Sep 19 '22 22:09

Kipton Barros