Can a method argument serve as an implicit parameter for an implicit conversion?

The following code in a REPL session:

case class Foo(x : Int) case class Bar(x : Int) case class Converter(y : Int) { def convert(x : Int) = x + y } implicit def fooFromBar(b : Bar)(implicit c : Converter) = Foo(c convert (bx)) def roundaboutFoo(x : Int, converter : Converter) : Foo = Bar(x) 

Gives me this error:

error: could not find an implicit value for parameter c: Converter def roundaboutFoo (x: Int, converter: converter): Foo = Bar (x)

If this is not obvious (implied), then I try to make Bar(x) implicitly converted to Foo . The implicit conversion itself is parameterized by the implicit Converter . The time I want to use this conversion has an instance of Converter available as a parameter to the method.

I expected this to die because I could not find the implicit conversion from Bar to Foo , since fooFromBar not a simple function from Foo to Bar , but I read in this question that implicit conversions can have implicit parameters, and indeed, the compiler, seems to have decided that this is part.

I found another question with a detailed answer specifically about where Scala is looking for things to fill in implications. But this only confirms my earlier understanding: Scala looks first in direct volume, and then at a bunch of other places that are not relevant here.

I wondered if there was something that Scala did not consider the local arguments of the method when considering the local range of values ​​to pass as implicit parameters. But adding something like val c = converter to roundaboutFoo does not change the error message I get.

Can this be done? If not, can someone help me figure out what to look for in order to recognize that such code is not working?

+1
scala implicit
source share
1 answer

converter must be either an implicit parameter:

 def roundaboutFoo(x: Int)(implicit converter: Converter): Foo = Bar(x) 

or assigned to the implicit value of val:

 def roundaboutFoo(x: Int, converter: Converter): Foo = { implicit val conv = converter Bar(x) } 

Regular parameters are not implicit and, therefore, are not searched when trying to fill in an implicit argument.

+6
source share

All Articles