How to pass a tuple argument the best way?

后端 未结 3 762
猫巷女王i
猫巷女王i 2021-02-01 02:12

How to pass a tuple argument the best way ?

Example:

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

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

Now I would like to

3条回答
  •  庸人自扰
    2021-02-01 02:48

    There is a special tupled method available for every function:

    val bar2 = (bar _).tupled  // or Function.tupled(bar _)
    

    bar2 takes a tuple of (Int, Int) (same as bar arguments). Now you can say:

    bar2(foo())
    

    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

    • How to apply a function to a tuple?

提交回复
热议问题