How to avoid repeating method parameter defaults

Hi,

When you write a method that forwards some parameters to another method, you have to repeat any parameter defaults:

def foo(x: Int = 42) = ???
def bar(
  x: Int = 42 // need to repeat this default
) = foo(x)

I find this rather irritating because I might want to change the default some day, and have the default apply everywhere in the codebase. OK, I can factor the default out in a val, but often I don’t control the definition of the function that I’m calling (e. g. foo might be defined in a library).

Could we make the defaults available somehow? Perhaps we could allow something like this:

def foo(x: Int = 42) = ???
def bar(
  x: Int = default(foo.x)
) = foo(x)

Perhaps this could even be implemented as a macro?

Defaults are currently positional, foo$default$1 or similar.

If foo is overloaded, a param name is not unique, though currently only one alternative can define defaults.

I’d like a direct way to declare a forwarder. Delegation by export doesn’t help.

A similar use case is class C(x, y, z) extends B(x, y, z).

Oh, maybe if they work this out for class params –

class C(a, _, _, _) extends B(x, y, z) { def m = a }

where C acquires the corresponding param names and defaults, then

def bar(_, y: Int) extends foo(x: Int) = { g(y); foo(x) }

Maybe bar also “acquires” the result type of foo.

That is off-the-cuff, but the class extension use case is an old complaint, especially because of shadowing, which would not apply for “signature extension” of methods.

Example solution with Selectable and transparent inline

edit: you’ve inspired me to create a blogpost, thanks!

3 Likes