R – How to convert X => Option[R] to PartialFunction[X,R]

partialfunctionscalascala-option

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](f: PartialFunction[X,R])(x: X) =
    if (f.isDefinedAt(x)) Some(f(x))
    else None

However, what if the task is opposite: suppose I have a function f getting X as an argument and returning Option[R] as a result. And I want to make a PartialFunction[X,R] out of it. What is the best way?

What I've come up with looks pretty ugly to my taste:

def optfToPf[X,R](f: X => Option[R]) : PartialFunction[X,R] = {
    object extractor {
        def unapply(x: X): Option[R] = f(x)
    }

    { case extractor(r) => r }
}

Is there some better way I missed?

Best Answer

Starting Scala 2.9, Function.unlift does precisely this:

def unlift[T, R](f: (T) => Option[R]): PartialFunction[T, R]

Turns a function T => Option[R] into a PartialFunction[T, R].

Related Topic