How to pass a tuple argument the best way?

左心房为你撑大大i 提交于 2019-12-02 17:55:40
Tomasz Nurkiewicz

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

Using tupled, as @Tomasz mentions, is a good approach.

You could also extract the tuple returned from foo during assignment:

val (x, y) = foo(5)
bar(x, y)

This has the benefit of cleaner code (no _1 and _2), and lets you assign descriptive names for x and y, making your code easier to read.

It is worth also knowing about

foo(...) match { case (a,b) => bar(a,b) }

as an alternative that doesn't require you to explicitly create a temporary fooResult. It's a good compromise when speed and lack of clutter are both important. You can create a function with bar _ and then convert it to take a single tuple argument with .tupled, but this creates a two new function objects each time you call the pair; you could store the result, but that could clutter your code unnecessarily.

For everyday use (i.e. this is not the performance-limiting part of your code), you can just

(bar _).tupled(foo(...))

in line. Sure, you create two extra function objects, but you most likely just created the tuple also, so you don't care that much, right?

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!