[英]How to implement type classes for recursive generics?
I would like to use type classes to provide a specialized implementation for a generic class. 我想使用类型类为泛型类提供专门的实现。 The trouble is the class is recursive, and I did not find a way how to write the code so that is works.
麻烦的是该类是递归的,而且我没有找到一种方法来编写代码,因此行之有效。 Here is my attempt:
这是我的尝试:
object Compare {
trait Compare[T <: Compare[T]] {
def compare(that: T): Boolean
}
trait IsCompare[T] {
def check: Boolean
}
trait LowerLevelImplicits {
implicit def defaultCompare[T]: IsCompare[T] = new IsCompare[T] {
def check = false
}
}
trait Implicits extends LowerLevelImplicits {
implicit def isCompare[T: Compare]: IsCompare[T] = new IsCompare[T] {
def check = true
}
}
case class MyClass(value: Int) extends Compare[MyClass] {
override def compare(that: MyClass) = this equals that
}
}
import Compare._
object Main extends App with Implicits {
def matchArray[T: IsCompare](array: Array[T]) = {
if (implicitly[IsCompare[T]].check) {
println("Using isCompare")
} else {
println("Not using isCompare")
}
}
}
The error is: 错误是:
Error:(17, 29) type arguments [T] do not conform to trait Compare's type parameter bounds [T <: Compare.Compare[T]]
错误:(17,29)类型参数[T]不符合特征比较的类型参数范围[T <:Compare.Compare [T]]
implicit def isCompare[T: Compare]: IsCompare[T] = new IsCompare[T] {
尝试将isCompare
的方法签名更改为:
implicit def isCompare[T <: Compare[T]]: IsCompare[T] = //...
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.