是否有更好/更少的锅炉板方法来实现类型类的实例?一个简单的例子:
trait Equal[A]{
def equals(a: A, b: A): Boolean = a ==b
}
object Equal{
def apply[A: Equal] = implicitly[Equal[A]]
implicit def IntEqual = new Equal[Int]{
def equal(a: Int, b: Int): Boolean = a == b
}
implicit def OptionEqual = new Equal[Option]{
def equal(a: Option, b: Option): Boolean = a == b
// Implicit instances for all desired types is tedious
}
答案 0 :(得分:4)
定义一个方法,该方法将函数作为输入并为您创建类型类实例:
def eqInstance[A](f: (A, A) => Boolean): Equal[A] = new Equal[A] {
def equal(a: A, b: A): Boolean = f(a,b)
}
那么你的类型类实例可以更加简洁:
val intEqual = eqInstance[Int](_ == _)