1

Is it possible to assign two values at once in scala? I mean code like:

var a: Int = 0
var b: Int = 0

(a, b) = methodReturningTupleOfInts()

Where of course methodReturningTupleOfInts returns (Int, Int)

amorfis
  • 15,390
  • 15
  • 77
  • 125

1 Answers1

1

Of course that is possible with values.

Being able to do such things with ease is the selling point of functional languages.

def myMethod(i:Int) = (i+1, i+2)

@Test
def testit() {
    val (a,b) = myMethod(5)

    Assert.assertEquals(a, 6)
    Assert.assertEquals(b, 7)
}

Please note we used a val above. What happens here is actually a pattern match to extract components of a compound term. But such is not possible with variables. It is thus not possible to do several assignments to at once to variables.

Because, changing values could have side effects. That would cause a lot of complexities, since then the order of performing this match and assignments would be relevant. Thus, if you really need a variable, then you need to extract the components of the tuple explicitly and assign them one by one

def myMethod(i:Int) = (i+1, i+2)

var (a,b) = (2,3)

@Test
def testit() {
    Assert.assertEquals(a, 2)
    Assert.assertEquals(b, 3)

    val result = myMethod(5)
    a = result._1
    b = result._2

    Assert.assertEquals(a, 6)
    Assert.assertEquals(b, 7)
}

Note the compound initialisation of the tuple (a,b) works and is OK. But it is not allow to alter it with a compound assignment. (a,b) = myMethod(5) would not compile

Ichthyo
  • 8,038
  • 2
  • 26
  • 32