How to collect a tuple into separate variables
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.
source to share
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;
()
}
source to share