使用scalaz的===用于adt

时间:2016-07-05 15:41:45

标签: scala typeclass scalaz7

我刚开始从eugene's blog post学习scalaz。我试图在我的代码中使用===但它返回一个编译错误     value === is not a member of object Red

这是我的代码

import scalaz._

sealed trait TrafficLight
case object Red extends TrafficLight
case object Yellow extends TrafficLight
case object Green extends TrafficLight

object Equality {

import Scalaz._

def eqInstance[A](f: (A,A) => Boolean): Equal[A] = new Equal[A]{
    def equal(a1: A, a2: A): Boolean = f(a1,a2)    
}

def trafficLightEqualFunction(a1: TrafficLight, a2: TrafficLight): Boolean = (a1, a2) match {
    case (Red, Red) => true
    case (Yellow, Yellow) => true
    case (Green, Green) => true
    case _ => false
}

implicit val trafficLightEqual: Equal[TrafficLight] = eqInstance(trafficLightEqualFunction)

def main(args: Array[String]){
    println(Red === Red)
}

}

1 个答案:

答案 0 :(得分:1)

这正是他的博客所抱怨的。 Red的类型为Red.type,此类型没有scalaz.Equal的实例,因为Equal是不变的,所以尽管如此:

Red <: TrafficLight

没有关注

Equal[Red] <: Equal[TrafficLight]

您可以通过让Scala将Red视为TrafficLight来修改它:

println((Red:TrafficLight) === (Red:TrafficLight))