scala 地图操作中的元组解包

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6905207/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-22 03:17:33  来源:igfitidea点击:

Tuple Unpacking in Map Operations

scalamapiteratortuplesiterable-unpacking

提问by duckworthd

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?

这是愚蠢的。我怎样才能解决这个问题?

回答by Nicolas

A work around is to use case:

解决方法是使用case

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

回答by thoredge

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 }

回答by user unknown

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.

似乎是一种简短但可读的形式。

回答by Kim Stebel

Another option is

另一种选择是

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

回答by Xavier Guihot

Note that with Dotty(foundation of Scala 3), parameter untuplinghas been extended, allowing such a syntax:

请注意,使用Dotty(foundation of Scala 3)扩展了参数解组,允许使用以下语法:

// 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.

其中 each_指的是为了关联的元组部分。

回答by Yahor

I think for comprehensionis the most natural solution here:

我认为理解是这里最自然的解决方案:

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