Search code examples
scaladefault-parameters

passing on default parameter in scala?


Please consider the following example

def foo(a: Int, b: Int = 100) = a + b
def bar(a: Int, b: Int = 100) = foo(a, b) * 2

This works, but note I have to supply the same default value to b in both functions. My intention is actually the following

def bar(a: Int, b: Int) = foo(a, b) * 2
def bar(a: Int)    = foo(a) * 2

But this becomes cumbersome when you have more optional arguments, and additional functions in the chain (such as baz that invokes bar in the same manner). Is there a more concise way to express this in scala?


Solution

  • I don't think there is; if you compose foo with a doubling function:

    val bar = (foo _).curried((_: Int)) andThen ((_: Int) *2)
    // (please, please let there be a simpler way to do this...)
    

    you lose the default arguments, because function objects don't have them.

    If it's worth it in your use-case, you could create a case class containing your arguments which you pass instead of multiple individual ones, e.g.

    case class Args(a: Int, b: Int = 100, c: Int = 42, d: Int = 69)
    def foo(args: Args) = { import args._; a + b + c + d }
    def bar(args: Args) = foo(args) * 2