Tuple Unpacking in Map Operations

≡放荡痞女 提交于 2019-11-28 03:45:23

A work around is to use case :

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

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 }

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.

Another option is

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

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.

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