This is something I\'ve wondered about for a while. I see this pattern a lot:
if (pf.isDefinedAt(in)) pf(in)
By breaking this up into two s
There is a conversation going on about this right now on the scala-internals mailing list. Martin Odersky has suggested a new type: FunctionWithDefault. Martin talks not only of a run-time penalty, but a compile time penalty (of class file bloat) of using PartialFunction:
First, we need to generate the pattern matching code twice, once in the apply and then again in the isDefinedAt. Second, we also need to execute the code twice, first to test whether the function is applicable, and then to actually apply it.
The answer to your question is essentially "yes" and and this behaviour (of PartialFunction) will not change either due to backwards-compatibility issues (for example, what if the isDefinedAt is side-effecting).
The new type being proposed, FunctionWithDefault has no isDefinedAt and has a method:
trait FunctionWithDefault[-I, +O] {
def applyOrElse[OO >: O](i : I, default : I => OO) : OO
}
which acts a bit like Options getOrElse method.
I have to say that, as usual, I cannot imagine this inefficiency poses any sort of performance problem in the overwhelming majority of cases.