【发布时间】:2015-09-05 00:06:36
【问题描述】:
我正在编写一个类型类来在类型之间进行转换,我注意到隐式对象上的 unapply 方法有一些不寻常的地方。具体的
object IntString extends PartialFunction[String, Int] {
def isDefinedAt(x: String) = Try(x.toInt).isSuccess
def apply(v1: String) = v1.toInt
def unapply(a:String):Option[Int] = if(this.isDefinedAt(a)) Some(this.apply(a)) else None
}
val s = "1000"
val IntString(i) = s
效果很好,但是
implicit object IntString extends PartialFunction[String, Int] {
def isDefinedAt(x: String) = Try(x.toInt).isSuccess
def apply(v1: String) = v1.toInt
def unapply(a:String):Option[Int] = if(this.isDefinedAt(a)) Some(this.apply(a)) else None
}
val s = "1000"
val IntString(i) = s
在 apply 方法处提供 StackOverflow。我希望能够让对象是隐式的,这样我就可以做类似的事情
def parse[A,B](a:A)(implicit ev:PartialFunction[A,B]) = ev(a)
除了显式应用/取消应用。
【问题讨论】: