3

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...

4 Answers 4

4

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.

Sign up to request clarification or add additional context in comments.

1 Comment

All good answers here, but this one is the cleanest from the caller's perspective, and that's what I'm after. Thanks!
2

How about:

def foo(dbOption: Option[Database] = None)(implicit ctx: Context) {
  val db = dbOption.getOrElse(ctx.defaultDB)
  ...
}

Comments

1

This:

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

Of course, it isn't implicit. You might be able to make it implicit with a trick like this:

def foo(implicit ctx:Context) = {
  class XXX {
    def apply(db:Database = ctx.defaultDB) = ...
  }
  new XXX(ctx)
}

However, that won't work like you expect, because foo(x) will pass x as the implicit, and foo()(x) will give an error. Only foo.apply(x) will work, and that sucks.

Comments

1

How about

def foo(db: Database = implicitly[Context].defaultDB) = ???

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.