How to pass a tuple argument the best way?

后端 未结 3 757
猫巷女王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 03:12

    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?

提交回复
热议问题