如何实现递归泛型的类型类?

时间:2018-10-08 12:32:42

标签: scala generics typeclass

我想使用类型类为泛型类提供专门的实现。麻烦的是该类是递归的,而且我没有找到一种方法来编写代码,因此行之有效。这是我的尝试:

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")
    }
  }


}

错误是:

  

错误:(17,29)类型参数[T]不符合特征比较类型参数的范围[T <:Compare.Compare [T]]

implicit def isCompare[T: Compare]: IsCompare[T] = new IsCompare[T] {

1 个答案:

答案 0 :(得分:2)

尝试将isCompare的方法签名更改为:

implicit def isCompare[T <: Compare[T]]: IsCompare[T] = //...