有没有办法将PartialFunction[Int,_]
转换为PartialFunction[Any,_]
?
以下代码抛出ClassCastException
val f: PartialFunction[Int, _] = ...
f.asInstanceOf[PartialFunction[Any,Any]].isDefinedAt("a")
答案 0 :(得分:4)
将其包装在一个新的部分函数中,该函数对于非Int
类型的输入未定义:
val g: PartialFunction[Any, Any] = { case x: Int if f isDefinedAt x => f(x) }
答案 1 :(得分:0)
您可以将部分功能包装在新的PartialFunction
中,如同已建议的那样:
val g: PartialFunction[Any, Any] = {
case x: Int if f isDefinedAt x => f(x)
}
另一种选择是扩展PartialFunction
并手动覆盖apply
和isDefined
。您甚至可以使用匿名类来完成此操作。例如:
new PartialFunction[Any, Any] {
def apply(x: Any) = f(x.asInstanceOf[Int])
def isDefinedAt(x: Any) = x.isInstanceOf[Int] && f.isDefinedAt(x.asInstanceOf[Int])
}
您也可以使用Function.unlift
和PartialFunction.lift
或PartialFunction.condOpt
:
import Function._
val g = unlift[Any, Any] {
case x: Int => f.lift(x)
case _ => None
}
//Alternative with condOpt
import PartialFunction._
val g = unlift(condOpt(_ : Any) { case x: Int => f.lift(x) }.flatten)
如果这很常见,你甚至可以用所需的方法来丰富PartialFunction
:
implicit class RichPartialFunction(val pf: PartialFunction[Int, Any]) extends AnyVal {
implicit def withAnyDomain = new PartialFunction[Any, Any] {
def apply(x: Any) = pf(x.asInstanceOf[Int])
def isDefinedAt(x: Any) = x.isInstanceOf[Int] && pf.isDefinedAt(x.asInstanceOf[Int])
}
}