gpt4 book ai didi

scala - 如何以最佳方式传递元组参数?

转载 作者:行者123 更新时间:2023-12-03 07:55:45 25 4
gpt4 key购买 nike

如何以最佳方式传递元组参数?

例子:

def foo(...): (Int, Int) = ...

def bar(a: Int, b: Int) = ...

现在我想传递 foo 的输出至 bar .这可以通过以下方式实现:
val fooResult = foo(...)
bar(fooResult._1, fooResult._2)

这种方法看起来有点难看,尤其是当我们处理 n 时。 -元组与 n > 2 .此外,我们必须将 foo 的结果存储在一个额外的值中,否则 foo必须使用 bar(foo._1, foo._2) 多次执行.

有没有更好的方法来传递元组作为参数?

最佳答案

有专门的tupled可用于每个函数的方法:

val bar2 = (bar _).tupled  // or Function.tupled(bar _)
bar2采用 (Int, Int) 的元组(与 bar 参数相同)。现在你可以说:
bar2(foo())

如果您的方法实际上是函数(注意 val 关键字),则语法会更令人愉快:
val bar = (a: Int, b: Int) => //...
bar.tupled(foo())

也可以看看
  • How to apply a function to a tuple?
  • 关于scala - 如何以最佳方式传递元组参数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12230698/

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