monkjack monkjack - 1 month ago 8
Scala Question

Scala total function as partial function

Since a total function is a special case of a partial function, I think I should be able to return a function when I need a partial.

Eg,

def partial : PartialFunction[Any,Any] = any => any


Of course this syntax fails to compile. My question is, is it possible to do this, and if so what do I need to do to get the syntax right.

I know I can do the following, but this is just an out-of-curiousity-question

def partial : PartialFunction[Any,Any] = {
case any => any
}

Answer

You could use PartialFunction.apply method:

val partial = PartialFunction[Any,Any]{ any => any }

You could import this method if you want to make it shorter:

import PartialFunction.{apply => pf}
val partial = pf[Any,Any]{ any => any }