scalatuples

How to collect tuple into separate variables


def giveMeTuple: Tuple2[String, String] = {
    Tuple2("one", "two")
}

def testFive: Unit = {
    val one, two = giveMeTuple
    println(one)
    println(two)
    ()
}

testFive

Produces:

(one,two)
(one,two)

But I was expecting:

one
two

What is going on with the initialization of one and two?


Solution

  • Almost there. This is what you need:

    val (one, two) = giveMeTuple
    

    With your current implementation of

    val one, two = giveMeTuple
    

    you are saying: initialize one with value returned by giveMeTuple and initialize two value returned by giveMeTuple (in this case giveMeTuple will be called twice).

    Another similar example is:

    val one, two = 1
    

    where both will be initialized to value 1.

    Instead you want to deconstruct the value return by giveMeTuple and take the first and second values from the tuple. In that case giveMeTuple will be called only once of course.