映射操作中的元组解包
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.我该如何解决这个问题?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
解决方法是使用
case
:A work around is to use
case
:我喜欢元组函数;它既方便又重要的是,输入安全:
I like the tupled function; it's both convenient and not least, type safe:
似乎
如果您多次需要参数,或者需要不同的顺序,或者在嵌套结构中,为什么不使用 _ 不起作用,
是一种简短但可读的形式。
Why don't you use
If you need the parameters multiple time, or different order, or in a nested structure, where _ doesn't work,
seems to be a short, but readable form.
另一种选择是
Another option is
从 Scala 3 开始,参数 untupling 已得到扩展,允许这样的语法:
其中每个
_
指的是关联的元组部分。Starting in
Scala 3
, parameter untupling has been extended, allowing such a syntax:where each
_
refers in order to the associated tuple part.我认为 用于理解 是这里最自然的解决方案:
I think for comprehension is the most natural solution here: