As long as we have a PartialFunction[X,R] it\'s very easy to convert it to a function returning Option[R], e.g.
def pfToOptf[X, R](
I suppose you could override apply and isDefinedAt by hand, but I'd do it the way you find ugly.
def optfToPf[X,R](f: X => Option[R]) = new PartialFunction[X,R] {
def apply(x: X): R = f(x).get
def isDefinedAt(x: X): Boolean = f(x) != None
}
Testing:
scala> val map = Map(1 -> 2)
map: scala.collection.immutable.Map[Int,Int] = Map(1 -> 2)
scala> map(1)
res0: Int = 2
scala> def mapOpt(key: Int) = map.get(key)
mapOpt: (key: Int)Option[Int]
scala> mapOpt(1)
res1: Option[Int] = Some(2)
scala> mapOpt(2)
res2: Option[Int] = None
scala> val mapPf = optfToPf(mapOpt _)
mapPf: java.lang.Object with PartialFunction[Int,Int] =
scala> mapPf.isDefinedAt(2)
res3: Boolean = false
scala> mapPf.isDefinedAt(1)
res4: Boolean = true
scala> mapPf(1)
res5: Int = 2
scala> mapPf(2)
java.util.NoSuchElementException: None.get