Scala has a special type of function called a partial function, which extends normal functions -- meaning that a PartialFunction
instance can be used wherever Function1
is expected. Partial functions can be defined anonymously using case
syntax also used in pattern matching:
val pf: PartialFunction[Boolean, Int] = {
case true => 7
}
pf.isDefinedAt(true) // returns true
pf(true) // returns 7
pf.isDefinedAt(false) // returns false
pf(false) // throws scala.MatchError: false (of class java.lang.Boolean)
As seen in the example, a partial function need not be defined over the whole domain of its first parameter. A standard Function1
instance is assumed to be total, meaning that it is defined for every possible argument.