Tuple Unpacking in Map Operations

2019-01-16 09:44发布

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?

4条回答
SAY GOODBYE
2楼-- · 2019-01-16 10:04

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楼-- · 2019-01-16 10:14

A work around is to use case :

arrayOfTuples map {case (e1: Int, e2: String) => e1.toString + e2}
查看更多
Juvenile、少年°
4楼-- · 2019-01-16 10:17

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.

查看更多
等我变得足够好
5楼-- · 2019-01-16 10:19

Another option is

arrayOfTuples.map { 
    t => 
    val (e1,e2) = t
    e1.toString + e2
}
查看更多
登录 后发表回答