1

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?

goral
  • 1,275
  • 11
  • 17
  • possible duplicate of [What is the Scala identifier "implicitly"?](http://stackoverflow.com/questions/3855595/what-is-the-scala-identifier-implicitly) – Jatin Aug 11 '14 at 09:13

1 Answers1

4

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.

Community
  • 1
  • 1
Jatin
  • 31,116
  • 15
  • 98
  • 163
  • I think I got it simultaneously to you posting this answer :) I have been having problems with forgeting this quirks recently. Need more coding I guess. – goral Aug 11 '14 at 09:29