【发布时间】:2015-11-21 21:07:51
【问题描述】:
我在 scala 中有一个 typeclass 模式,我想要一个可以针对任何类型调用的方法,并根据范围内是否有适当的 typeclass 来返回一个选项。具体来说,我有:
trait Truthy[A] {
def toBoolean(a:A):Boolean
def unapply(a:Any):Option[Boolean]
}
object Truthy {
implicit object IntTruthy extends Truthy[Int] {
def toBoolean(i:Int) = i == 1
def unapply(a:Any) = a match {
case i:Int => Some(toBoolean(i))
case _ => None
}
}
implicit object BoolTruthy extends Truthy[Boolean] {
def toBoolean(b:Boolean) = b
def unapply(a:Any) = a match {
case i:Boolean => Some(toBoolean(i))
case _ => None
}
}
implicit object StringTruthy extends Truthy[String] {
def toBoolean(s:String) = Set("t", "true", "yes", "y").contains(s.toLowerCase)
def unapply(a:Any) = a match {
case i:String => Some(toBoolean(i))
case _ => None
}
}
def truthy[A](a:A)(implicit ev:Truthy[A]) = ev.toBoolean(a)
}
当我知道参数的类型时,truthy 方法很好,但是我正在使用来自缺少该类型信息的源的数据,所以我想要一个带有签名 Any => Option[Boolean] 的函数,它将尝试所有范围内的Truthy 实现,如果可以找到则返回结果。显然我可以写
def getTruth(a:Any) = a match {
case IntTruthy(b) => Some(b)
case BoolTruthy(b) => Some(b)
case StringTruthy(b) => Some(b)
case _ => None
}
但这会破坏类型类“开放”的全部目的。
【问题讨论】: