scala - 在 scala 的函数参数中提取元组的快捷方式

标签 scala

val list = List((1,2), (3,4))

list.map(tuple => {
  val (a, b) = tuple
  do_something(a,b)
})

// the previous can be shortened as follows
list.map{ case(a, b) =>
  do_something(a,b)
}

// similarly, how can I shorten this (and avoid declaring the 'tuple' variable)?
def f(tuple: (Int, Int)) {
  val (a, b) = tuple
  do_something(a,b)
}

// here there two ways, but still not very short,
// and I could avoid declaring the 'tuple' variable
def f(tuple: (Int, Int)) {
  tuple match {
    case (a, b) => do_something(a,b)
  }
}

def f(tuple: (Int, Int)): Unit = tuple match {
  case (a, b) => do_something(a,b)
}

最佳答案

使用元组

scala> def doSomething = (a: Int, b: Int) => a + b
doSomething: (Int, Int) => Int

scala> doSomething.tupled((1, 2))
res0: Int = 3

scala> def f(tuple: (Int, Int)) = doSomething.tupled(tuple)
f: (tuple: (Int, Int))Int

scala> f((1,2))
res1: Int = 3

scala> f(1,2) // this is due to scala auto-tupling
res2: Int = 3

tupled 是为每个N >= 2FunctionN 定义的,并返回一个期望包含在元组中的参数的函数。

关于scala - 在 scala 的函数参数中提取元组的快捷方式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26578968/

相关文章:

scala - Scala最终阻止关闭/刷新资源

scala - Scala 中的 Spark 爆炸 - 将爆炸列添加到行

斯卡拉 : Code for pattern match

scala - Scala 中列表列表的模式匹配

scala - `saveAsTable` 之后无法从 Hive 查询 Spark DF - Spark SQL 特定格式,与 Hive 不兼容

scala - 为什么scalaz-stream中有两种网络io的实现?

regex - 斯卡拉玩 : Invalid '@' symbol in email regex

java - 分布式系统设计问题 - Scala

scala - 验证 Datomic 实体 ID 是否有效

java - 如何以编程方式将两个文本文件中的 "changes"合并到一个文件中?