How to collect a tuple into separate variables

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

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

testFive

      

Outputs:

(one,two)
(one,two)

      

But I expected:

one
two

      

What happens to the initialization one

and two

?

+3


source to share


2 answers


Almost there. This is what you need:

val (one, two) = giveMeTuple

      

FROM

val one, two = giveMeTuple

      

you say: initialize one

with the return value giveMeTuple

and initialize the two

return value giveMeTuple

(in this case giveMeTuple

will be called twice)



Another similar example is

val one, two = 1

      

where both will be value-initialized 1

Instead, you want to deconstruct the return value giveMeTuple

and take the first and second values ​​from the tuple. In this case, it giveMeTuple

will only be called once.

+3


source


You are missing a parenthesis:

val (one, two) = giveMeTuple

      

If we decompile the above code, we can see that it is just a Tuple pattern that is part of the Scalas Pattern Matching feature:



def main(args: Array[String]): Unit = {                                                                                              
  private[this] val x$1: (String, String) = (TupleTest.this.giveMeTuple: (String, String) @unchecked) match { 
    case (_1: String, _2: String)(String, String)((one @ _), (two @ _)) => scala.Tuple2.apply[String, String](one, two)              
  };                                                                                                                                 
  val one: String = x$1._1;                                                                                                          
  val two: String = x$1._2;                                                                                                          
  ()
}        

      

Whereas your example is a double call to the same method and assignment to a new value:

def giveMeTuple: (String, String) = scala.Tuple2.apply[String, String]("one", "two"); 
def main(args: Array[String]): Unit = {                                               
   val one: (String, String) = TupleTest.this.giveMeTuple;                             
   val two: (String, String) = TupleTest.this.giveMeTuple;                             
   ()                                                                                  
 }                                                                                     

      

+2


source







All Articles