It is quite possible that to know whether a function is defined at some point, a significant part of computing its value has to be done. In a PartialFunction
, when implementing isDefined
and apply
, both methods will have to do that. What to do is this common job is costly?
There is the possibility of caching its result, hoping that apply will be called after isDefined. Definitely ugly.
I often wish that PartialFunction[A,B]
would be Function[A, Option[B]]
, which is clearly isomorphic. Or maybe, there could be another method in PartialFunction
, say applyOption(a: A): Option[B]
. With some mixins, implementors would have a choice of implementing either isDefined and apply or applyOption. Or all of them to be on the safe side, performance wise. Clients which test isDefined
just before calling apply would be encouraged to use applyOption
instead.
However, this is not so. Some major methods in the library, among them collect
in collections require a PartialFunction
. Is there a clean (or not so clean) way to avoid paying for computations repeated between isDefined and apply?
Also, is the applyOption(a: A): Option[B]
method reasonable? Does it sound feasible to add it in a future version? Would it be worth it?