如何以最佳方式传递元组参数? [英] How to pass a tuple argument the best way?
问题描述
如何以最佳方式传递元组参数?
How to pass a tuple argument the best way ?
示例:
def foo(...): (Int, Int) = ...
def bar(a: Int, b: Int) = ...
现在我想将 foo
的输出传递给 bar
.这可以通过以下方式实现:
Now I would like to pass the output of foo
to bar
. This can be achieved with:
val fooResult = foo(...)
bar(fooResult._1, fooResult._2)
这种方法看起来有点难看,尤其是当我们用 n > 处理
.此外,我们必须将 foo 的结果存储在一个额外的值中,否则必须使用 n
-元组时.2bar(foo._1, foo._2)
多次执行 foo
.
This approach looks a bit ugly, especially when we deal with a n
-tuple with n > 2
. Also we have to store the result of foo in an extra value, because otherwise foo
has to be executed more than once using bar(foo._1, foo._2)
.
是否有更好的方法将元组作为参数传递?
推荐答案
每个函数都有一个特殊的tupled
方法:
There is a special tupled
method available for every function:
val bar2 = (bar _).tupled // or Function.tupled(bar _)
bar2
采用 (Int, Int)
元组(与 bar
参数相同).现在你可以说:
bar2
takes a tuple of (Int, Int)
(same as bar
arguments). Now you can say:
bar2(foo())
如果你的方法实际上是函数(注意 val
关键字),语法会更令人愉快:
If your methods were actually functions (notice the val
keyword) the syntax is much more pleasant:
val bar = (a: Int, b: Int) => //...
bar.tupled(foo())
另见
- 如何将函数应用于元组?
这篇关于如何以最佳方式传递元组参数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!