如何通过一个元组参数的最佳方式? [英] How to pass a tuple argument the best way?

查看:95
本文介绍了如何通过一个元组参数的最佳方式?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何通过一个元组参数的最佳方式?

How to pass a tuple argument the best way ?

例如:

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

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

现在我想的输出传递到。这可以通过以下方式实现:

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 元组与 N'GT; 2 。此外,我们必须foo的结果存储在一个额外的价值,否则已被多次使用栏(foo._1更多的执行, foo._2)

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)(等同于栏<一个元组/ code>参数)。现在,你可以说:

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())

另请参见


  • 斯卡​​拉
  • 应用一个函数的元组

    See also

    • Applying a function to a tuple in Scala
    • 这篇关于如何通过一个元组参数的最佳方式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆