12

Consider the following:

def f(implicit a: String, y: Int = 0) = a + ": " + y
implicit val s = "size"
println(f(y = 2))

The last expression causes the following error:

not enough arguments for method f: (implicit a: String, implicit y:
Int)java.lang.String. Unspecified value parameter a.

However, if you provide a default value to the implicit parameter a, there is no issue:

def f(implicit a: String = "haha!", y: Int = 0) = a + ": " + y
implicit val s = "size"
println(f(y = 2))

But the last line prints

haha!: 2

while I would have expected

size: 2

So the implicit value 's' is not picked up. If you instead don't provide any parameters to f and just call

println(f)

then the implicit value is picked up and you get

size: 0

Can someone shed some light on what's going on here?

0

3 Answers 3

16

Try

println(f(y = 2, a = implicitly))

Once you start specifying parameters, you can't go back. It's either the whole list is implicit or none of it is.

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

Comments

4

Implicit parameters should go separately -- first, and in the end of method definition -- second. Like this:

def f(y: Int = 0)(implicit a: String) = a + ": " + y
implicit val s = "size"
println(f(y = 2))

Ouputs

size: 2

1 Comment

To use first default parameter must call f() .
0

Along the lines of what jsuereth said, you could define your function as

def f(a: String = implicitly, y:Int = 0) = a + ": " + y

Or in the way I'm more used to seeing,

def f(y:Int = 0)(implicit a: String) = a + ": " + y

1 Comment

You should check which implicit scope that implicitly is using. I don't think it's the same as the second option.

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.