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]]
implicit def isCompare[T: Compare]: IsCompare[T] = new IsCompare[T] {