Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 481
user881423 Avatar asked Mar 11 '26 01:03

user881423


1 Answers

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
like image 107
Luigi Plinge Avatar answered Mar 14 '26 00:03

Luigi Plinge