I am designing an API using type classes in some cases however I have encountered a problem with implicit resolution. As shown below, if there is an implicit object for type A but an object of type B extends A
is passed to the method, then an implicit object cannot be found. Is there a way to make this work or do callers have to put implicit objects into scope for each subclass?
Here is an example:
class A
class B extends A
class T[+X]
object T {
implicit object TA extends T[A]
}
def call[X:T](x:X) = println(x)
// compiles
call(new A)
// doesn't compile
call(new B)
var a = new A
// compiles
call(a)
a = new B
// compiles
call(a)
val b = new B
// doesn't compile
call(b)
This fails to compile with the following output:
/private/tmp/tc.scala:16: error: could not find implicit value for evidence parameter of type this.T[this.B] call(new B) ^ /private/tmp/tc.scala:28: error: could not find implicit value for evidence parameter of type this.T[this.B] call(b)