【发布时间】:2021-02-09 14:15:23
【问题描述】:
我是 typeclass 模式的新手,并且在 scala 中是隐式的,下面是我为测试此模式所做的代码 sn-p,但我不知道为什么 compareB 方法无法找到参数的隐式值 wrapper ,即使我声明了一个 IntWrapper[Int] 类型的隐式字段。
有人知道 typeclass 中的隐式是如何解决的吗?为什么下面的代码不能编译?
谢谢
trait IntWrapper[T]{
def test: Boolean
}
trait ProductComparator[T] extends Serializable{
def compare(p1 : T, p2: T): Boolean
}
object ProductComparator{
def apply[A](implicit cmp: ProductComparator[A]) : ProductComparator[A] = cmp
implicit def w: IntWrapper[Int] =
new IntWrapper[Int] {
override def test: Boolean = true
}
implicit def CompareB[T <: Product, Repr <: HList, KRepr <: HList](implicit gen: LabelledGeneric.Aux[T, Repr], keys: Keys.Aux[Repr, KRepr], wrapper: IntWrapper[Int]) : ProductComparator[T] =
new ProductComparator[T] {
override def compare(p1: T, p2: T): Boolean = {
p1.productArity == p2.productArity
}
}
}
case class Emp(a: Int, b: Int)
object Demo extends App{
val comparator = implicitly[ProductComparator[Emp]]
}
【问题讨论】:
-
在
CompareB中,您实际上并没有使用任何隐式gen: LabelledGeneric.Aux[T, Repr], keys: Keys.Aux[Repr, KRepr], wrapper: IntWrapper[Int]。所以我想这只是一个例子。对吗?
标签: scala typeclass implicit shapeless