开发者

Swapping two vars in scala [duplicate]

This question already has an answer here: 开发者_开发知识库 Closed 11 years ago.

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 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?

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜