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?
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…