1
我正在写一个类型类型之间转换类型,我注意到一些不寻常的方法隐式对象上的不正常。具体scala StackOverflow上隐式对象不适用
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)
除了显式的apply/unapply。
谢谢!这是对发生的事情的一个非常清楚的解释。我以为有某种意想不到的暗示技巧在继续,但我不确定是什么。我实际上想继续扩展'PartialFunction'(我的实际实现有一个扩展它的类型类),这样我就可以对'orElse'和'和Then'做一些事情,但根据你的回答,我把'v1.toInt'改为'Integer.parseInt(v1)',它工作。 –