gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 01:44:24 25 4
gpt4 key购买 nike

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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com