Tuple Unpacking in Map Operations

后端 未结 6 1542
慢半拍i
慢半拍i 2020-12-07 15:46

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, \"         


        
相关标签:
6条回答
  • 2020-12-07 15:57

    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.

    0 讨论(0)
  • 2020-12-07 16:04

    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.

    0 讨论(0)
  • 2020-12-07 16:06

    Another option is

    arrayOfTuples.map { 
        t => 
        val (e1,e2) = t
        e1.toString + e2
    }
    
    0 讨论(0)
  • 2020-12-07 16:13

    I think for comprehension is the most natural solution here:

    for ((e1, e2) <- arrayOfTuples) yield {
      e1.toString + e2
    }
    
    0 讨论(0)
  • 2020-12-07 16:14

    A work around is to use case :

    arrayOfTuples map {case (e1: Int, e2: String) => e1.toString + e2}
    
    0 讨论(0)
  • 2020-12-07 16:17

    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 }
    
    0 讨论(0)
提交回复
热议问题