我经常发现自己正在使用元组的列表,序列和迭代器,并希望做类似以下的事情,
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
}
这真是太傻了。我怎么能绕过这个?
答案 0 :(得分:117)
解决方法是使用case
:
arrayOfTuples map {case (e1: Int, e2: String) => e1.toString + e2}
答案 1 :(得分:29)
我喜欢tupled功能;它既方便又简单,类型安全:
import Function.tupled
arrayOfTuples map tupled { (e1, e2) => e1.toString + e2 }
答案 2 :(得分:15)
为什么不使用
arrayOfTuples.map {t => t._1.toString + t._2 }
如果您需要多个时间或不同顺序的参数,或者在嵌套结构中,_不起作用,
arrayOfTuples map {case (i, s) => i.toString + s}
似乎是一种简短但可读的形式。
答案 3 :(得分:7)
另一种选择是
arrayOfTuples.map {
t =>
val (e1,e2) = t
e1.toString + e2
}
答案 4 :(得分:0)
请注意,Dotty
已扩展为parameter untupling(System.out.println(Arrays.toString(priorityQueue.toArray()));
的基础),允许使用以下语法:
Scala 3
每个// val tuples = List((1, "Two"), (3, "Four"))
tuples.map(_.toString + _)
// List[String] = List("1Two", "3Four")
所指的是相关联的元组部分。
答案 5 :(得分:0)
我认为for comprehension是最自然的解决方案:
for ((e1, e2) <- arrayOfTuples) yield {
e1.toString + e2
}