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?
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.
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 var
s 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?
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