Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scala named and default arguments in conjunction with implicit parameters

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?

like image 532
Martin Studer Avatar asked Feb 23 '12 16:02

Martin Studer


1 Answers

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.

like image 180
jsuereth Avatar answered Sep 28 '22 10:09

jsuereth