How to resolve implicit lookup by bounded generic?

◇◆丶佛笑我妖孽 提交于 2021-01-29 20:39:34

问题


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)


回答1:


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]]
  //...
}


来源:https://stackoverflow.com/questions/57495884/how-to-resolve-implicit-lookup-by-bounded-generic

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!