【问题标题】:How to resolve implicit lookup by bounded generic?如何通过有界泛型解决隐式查找?
【发布时间】:2019-12-21 01:56:56
【问题描述】:

我有一系列的类Foo:

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

我有一个类型类和所有 Foos 的实例:

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

我尝试从方法中获取类型类实例:

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

编译器抱怨No implicits found for parameter e: CanBar[T],即使我导入了所有CanBar[Foo] 实例。

我的假设是编译器正在寻找 T(即 Any 或 Foo)但没有找到。我是否正确,在这种情况下如何使它工作(没有宏)

【问题讨论】:

    标签: scala typeclass implicit context-bound


    【解决方案1】:

    编译器抱怨No implicits found for parameter e: CanBar[T],即使我导入了所有CanBar[Foo] 实例。

    CanBar[Foo] 不是CanBar[T]

    添加上下文绑定

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

    【讨论】:

    • 在这种情况下我相信def bar[T &lt;: Foo](foo: T)(implicit canBar: CanBar[T]) = {会更好。这样,就不需要隐式行了。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-11-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-05-25
    相关资源
    最近更新 更多