Unpacking packages in card operations

I often work with lists, sections, 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 agrees with this syntax. Instead, I finish writing,

 arrayOfTuples.map { t => val e1 = t._1 val e2 = t._2 e1.toString + e2 } 

This is just stupid. How can I get around this?

+70
iterator scala tuples iterable-unpacking map
Aug 01 '11 at 10:22
source share
5 answers

A workaround is to use case :

 arrayOfTuples map {case (e1: Int, e2: String) => e1.toString + e2} 
+117
Aug 01 2018-11-11T00:
source share

I like the interleave function; it is both convenient and no less safe:

 import Function.tupled arrayOfTuples map tupled { (e1, e2) => e1.toString + e2 } 
+29
Aug 02 2018-11-11T00:
source share

Why don't you use

 arrayOfTuples.map {t => t._1.toString + t._2 } 

If you need parameters several times, or in a different order, or in a nested structure where _ does not work,

 arrayOfTuples map {case (i, s) => i.toString + s} 

seems short but readable.

+15
Aug 02 2018-11-11T00:
source share

Another variant:

 arrayOfTuples.map { t => val (e1,e2) = t e1.toString + e2 } 
+7
Aug 01 2018-11-21T00:
source share

Note that in Dotty (the base of Scala 3 ), the parameter extension was expanded, which allowed the use of the following syntax:

 // val tuples = List((1, "Two"), (3, "Four")) tuples.map(_.toString + _) // List[String] = List("1Two", "3Four") 

where each _ refers to the associated part of the tuple.

0
May 21 '19 at 20:10
source share



All Articles