Reputation: 9325
I have a method that expects some implicit param of type String.
I have an object of class MyClass
which I want to pass to that method implicitly.
First, I'm making implicit conversion from MyClass
to String
.
If I pass object of MyClass
to the method which expects String
explicitly, it works fine.
But passing it implicitly causes compilation error:
could not find implicit value for parameter str: String someMethod()
Here is the code:
case class MyClass(str: String)
object MyClass {
implicit def myClassToString(myClass: MyClass): String = myClass.str
}
object Application extends App {
def someMethod()(implicit str: String) = println(str)
implicit val myClass = MyClass("Hello")
someMethod()(myClass) <-- WORKS
someMethod() <-- ERROR
}
Is it possible to pass implicitly converted variable implicitly?
P.S.: I cannot change someMethod
Upvotes: 4
Views: 525
Reputation: 9698
It cannot work because you don't have an implicit String value. What you do have is an implicit conversion from MyClass => String
, but not the string itself.
So what you need is to supply a String. Since you have the implicit conversion from MyClass to String, you can say:
def someMethod()(implicit str: String) = println(str)
implicit val myClass: String = MyClass("Hello") // conversion kicks in
someMethod() // error: no implicit string found in scope
This way in line 2 the implicit conversion kicks in, so by line 3 you have an implicit String ready to be passed in.
Note that if you keep the MyClass type, it can still work by explicitly providing the argument:
implicit val myClass: MyClass = MyClass("Hello")
someMethod(myClass)
So yeah, the line between what works and what doesn't seems a bit arbitrary. I'm not sure if it's caused by the amount of compiler hacks needed to make it work, or they simply wanted to prevent chaos from ensuing when doing such recursive implicit search. Probably the latter.
Upvotes: 4