Is there any way to create a PartialFunction
except through the case
statement?
I'm curious, because I'd like to express the following (scala pseudo ahead!)...
val bi = BigInt(_)
if (bi.isValidInt) bi.intValue
... as a partial function, and doing
val toInt : PartialFunction[String, Int] = {
case s if BigInt(s).isValidInt => BigInt(s).intValue
}
seems redundant since I create a BigInt
twice.
How about this?
Okay, I got this
I think you're looking for lift/unlift. lift takes a partial function and turns it into a function that returns an Option. Unlift takes a function with one argument that returns an option, and returns a partial function.
Closely related, you also want to look at this answer for information about cond and condOpt:
You can write out a
PartialFunction
"longhand" if you'd like:Not sure I understand the question. But here's my attempt: Why not create an extractor?
The other option is (and that may answer the question as to whether one can create
PartialFunction
other than with acase
literal):However since the idea of a partial function is that it's only partially defined, in the end you will still do redundant things -- you need to create a big int to test whether it's valid, and then in the function application you create the big int again...
I saw a project at Github that tried to come around this by somewhat caching the results from
isDefinedAt
. If you go down to the benchmarks, you'll see that it turned out to be slower than the default Scala implementation :)So if you want to get around the double nature of
isDefinedAt
versusapply
, you should just go straight for a (full) function that provides anOption[Int]
as result.