【问题标题】:How to implement type classes for recursive generics?如何为递归泛型实现类型类?
【发布时间】:2018-10-08 21:02:36
【问题描述】:

我想使用类型类来为泛型类提供专门的实现。问题是类是递归的,我没有找到一种方法来编写代码,这样就可以了。这是我的尝试:

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] 不符合 trait Compare 的类型参数界限 [T <: compare.compare>

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

【问题讨论】:

    标签: scala generics typeclass


    【解决方案1】:

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-05-05
      • 1970-01-01
      • 1970-01-01
      • 2018-10-29
      • 2020-02-19
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多