地图操作中的元组解包

我经常发现自己在使用 Tuples 的 List、 Seqs 和迭代器,并且想要做下面这样的事情:

val arrayOfTuples = List((1, "Two"), (3, "Four"))
arrayOfTuples.map { (e1: Int, e2: String) => e1.toString + e2 }

然而,编译器似乎从来没有同意这种语法,

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

这太傻了,我怎么才能避开这个问题呢?

48825 次浏览

A work around is to use case :

arrayOfTuples map {case (e1: Int, e2: String) => e1.toString + e2}

Another option is

arrayOfTuples.map {
t =>
val (e1,e2) = t
e1.toString + e2
}

Why don't you use

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

If you need the parameters multiple time, or different order, or in a nested structure, where _ doesn't work,

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

seems to be a short, but readable form.

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 }

Starting in Scala 3, parameter untupling has been extended, allowing such a syntax:

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

where each _ refers in order to the associated tuple part.

I think for comprehension is the most natural solution here:

for ((e1, e2) <- arrayOfTuples) yield {
e1.toString + e2
}