如何解决有界泛型的隐式查找? [英] How to resolve implicit lookup by bounded generic?
问题描述
我有一系列的Foo课:
I have a series of class Foo:
trait Foo
class Foo1 extends Foo
class Foo2 extends Foo
//...
并且我有一个类型类和所有Foos的实例:
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]]
//...
}
即使我导入了所有 CanBar [Foo]
实例,编译器仍会抱怨未找到参数e:CanBar [T]
的隐式变量.
The compiler complains No implicits found for parameter e: CanBar[T]
, even though I imported all the CanBar[Foo]
instances.
我的假设是编译器正在寻找T(它是Any或Foo)而没有找到任何T.我是正确的,在这种情况下(没有宏)如何使它工作
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)
推荐答案
即使我导入了所有
CanBar [Foo]
实例,编译器仍会抱怨未找到参数e:CanBar [T]
的隐式变量.
The compiler complains
No implicits found for parameter e: CanBar[T]
, even though I imported all theCanBar[Foo]
instances.
CanBar [Foo]
不是 CanBar [T]
.
添加上下文绑定
def bar[T <: Foo : CanBar](foo: T) = {
val canBar = implicitly[CanBar[T]]
//...
}
这篇关于如何解决有界泛型的隐式查找?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!