I frequently find myself working with Lists, Seqs, and Iterators of Tuples and would like to do something like the following,
val arrayOfTuples = List((1, "Two"), (3, "Four")) arrayOfTuples.map { (e1: Int, e2: String) => e1.toString + e2 }
However, the compiler never seems to agree with this syntax. Instead, I end up writing,
arrayOfTuples.map { t => val e1 = t._1 val e2 = t._2 e1.toString + e2 }
Which is just silly. How can I get around this?
Unpacking a tuple means splitting the tuple's elements into individual variables. For example: x, y = (1, 2) Code language: Python (python)
Unpacking Tuples When we put tuples on both sides of an assignment operator, a tuple unpacking operation takes place. The values on the right are assigned to the variables on the left according to their relative position in each tuple . As you can see in the above example, a will be 1 , b will be 2 , and c will be 3 .
Tuple packing refers to assigning multiple values into a tuple. Tuple unpacking refers to assigning a tuple into multiple variables.
Maps or hash tables are collections of key value pairs. Tuples are an immutable sequence of values and are used for aggregating values.
A work around is to use case
:
arrayOfTuples map {case (e1: Int, e2: String) => e1.toString + e2}
I like the tupled function; it's both convenient and not least, type safe:
import Function.tupled arrayOfTuples map tupled { (e1, e2) => e1.toString + e2 }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With