Search code examples
scalatypeclassimplicitcontext-bound

How to resolve implicit lookup by bounded generic?


I have a series of class Foo:

trait Foo
class Foo1 extends Foo
class Foo2 extends Foo
//...

and I have a type class and instances for all of the Foos:

trait CanBar[T] { def bar: Unit }
implicit val foo1: CanBar[Foo1] = null
implicit val foo2: CanBar[Foo2] = null

and I try to get the type class instance from a method:

def bar[T <: Foo](foo: T) = {
  val canBar = implicitly[CanBar[T]]
  //...
}

The compiler complains No implicits found for parameter e: CanBar[T], even though I imported all the CanBar[Foo] instances.

My assumption is that the compiler is looking for T (which is Any or Foo) and did not find any. Am I correct and how can I make it work in this case (without macros)


Solution

  • The compiler complains No implicits found for parameter e: CanBar[T], even though I imported all the CanBar[Foo] instances.

    CanBar[Foo] is not CanBar[T].

    Add context bound

    def bar[T <: Foo : CanBar](foo: T) = {
      val canBar = implicitly[CanBar[T]]
      //...
    }