Tuple Unpacking in Map Operations

笑着哭i 提交于 2019-11-27 00:11:50

问题


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?


回答1:


A work around is to use case :

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



回答2:


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 }



回答3:


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.




回答4:


Another option is

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



回答5:


Note that with Dotty (foundation of 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.




回答6:


I think for comprehension is the most natural solution here:

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


来源:https://stackoverflow.com/questions/6905207/tuple-unpacking-in-map-operations

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!