How to fix this typeclass example?

2019-08-10 20:32发布

问题:

This is a follow-up to my previous question:

Suppose I create the following test converter.scala:

trait ConverterTo[T] {
  def convert(s: String): Option[T]
}

object Converters {
  implicit val toInt: ConverterTo[Int] =
    new ConverterTo[Int] { 
      def convert(s: String) = scala.util.Try(s.toInt).toOption
    }
}

class A {
  import Converters._
  def foo[T](s: String)(implicit ct: ConverterTo[T]) = ct.convert(s)
}

Now when I tried to call foo in REPL it fails to compile:

scala> :load converter.scala
Loading converter.scala...
defined trait ConverterTo
defined module Converters
defined class A

scala> val a = new A()

scala> a.foo[Int]("0")
<console>:12: error: could not find implicit value for parameter ct: ConverterTo[Int]
          a.foo[Int]("0")
                    ^

回答1:

import Converters._ in class A does not cut it. You can remove it and the code will still compile. The moment the compiler needs to find in actual implicit is not in class A, where foo is just declared.

The compiler needs to find a ConverterTo[Int] in implicit scope at the moment you call a.foo[Int](..) that is in the REPL. So this is where the import needs to be.

Had object Converters and trait ConverterTo been named the same (so there would be a companion object) the import would not be needed.