Reputation: 1265
Hi I have an implicit method like:
implicit def strToOpt(str: String): Option[String] = Option(str)
and it works for simple conversion, but when I type
implicitly[String]
I get
error: could not find implicit value for parameter e: String
Does REPL have some limitations in term of finding implicits?
Upvotes: 1
Views: 104
Reputation: 31754
I think you have misunderstood implicitly
. It is defined as:
def implicitly[T](implicit e: T): T = e
Which roughly means, that implicitly[T]
will return you an object of type T
which is available in current scope (scope is not the precise word. Compiler looks at many places)
In your case doing implicitly[String]
simply means that some object of type String
is available.
For example this is valid:
scala> implicit val x = "Hey"
x: String = Hey
scala> implicitly[String]
res12: String = Hey
But what you rather need to do is:
scala> implicitly[(String) => Option[String]]
res10: String => Option[String] = <function1>
scala> res10("asd")
res11: Option[String] = Some(456)
PS: Note answer by @Ende Neu works as:
implicitly[Option[String]]("123")
Doing implicitly[Option[String]]("123")
, in the implicitly function it takes T
as argument which is String
. But you have manually provided Option[String]
as type parameter of method. So the compiler searches for a function again (by using implicitly
again) that does String => Option[String]
which it finds in your function.
Upvotes: 4