user3663882 user3663882 - 3 months ago 16
Scala Question

Calling method with an implicit parameter

I have the following method:

def test[T](implicit ev: T <:< Int, t : T) = println(t)


How can I call it? I tried

test(10)


But the compile prints out the following error:

Error:(19, 9) not enough arguments for method test: (implicit ev: <:<[T,Int], implicit t: T)Unit.
Unspecified value parameter t.
test(10)
^


First of all, I thought that we could just omit implicit parameters and specify only explicit ones. And secondly, why does it's saying that that the parameter
t
is implicit?

implicit t: T


How does it actually work?

Answer

First of all, I thought that we could just omit implicit parameters and specify only explicit ones.

You either specify all the implicits in the list, or you don't specify them at all. According to the specification, if one parameter is marked as implicit, the entire argument list is marked as well:

An implicit parameter list (implicit p1, ……, pn) of a method marks the parameters p1, …, pn as implicit.


secondly, why does it's saying that that the parameter t is implicit?

Because of what was answered in your first part.

If you still want to invoke it like that, you can use implicitly:

test(implicitly, 10)

Generally, it is recommended that you require an implicit in a separate argument list:

def test[T](i: Int)(implicit ev: T <:< Int) = println(t)