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?

j0k
  • 22,600
  • 28
  • 79
  • 90
Martin Studer
  • 2,213
  • 1
  • 18
  • 23

3 Answers3

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.

jsuereth
  • 5,604
  • 40
  • 40
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
Vadim Samokhin
  • 3,378
  • 4
  • 40
  • 68
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
Dylan
  • 13,645
  • 3
  • 40
  • 67
  • 2
    You should check which implicit scope that implicitly is using. I don't think it's the same as the second option. – jsuereth Mar 02 '12 at 16:45