Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scala default parameters from other parameters

Tags:

scala

I'm trying to do something like the following, and the compiler is not happy...

def foo(db: Database = ctx.defaultDB)(implicit ctx: Context)

That is, if db isn't specified, use ctx to look up the default. The compiler didn't like this version so I tried this:

def foo(ctx: Context, db: Database = ctx.defaultDB)

Compiler didn't like that either...

like image 726
Greg Avatar asked May 09 '26 02:05

Greg


1 Answers

There are many limitations on default parameter values.

I suggest overloading:

def foo(db: Database)(implicit ctx: Context) = ...

def foo(implicit ctx: Context): Type = foo(ctx.defaultDB)(ctx)

I'm not sure what the exact requirement is, but my quick testing suggests you have to make the return type on the 2nd overload explicit.

like image 200
Randall Schulz Avatar answered May 11 '26 15:05

Randall Schulz



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!