Scala Language Partial Functions Basic syntax

Help us to keep this website almost Ad Free! It takes only 10 seconds of your time:
> Step 1: Go view our video on YouTube: EF Core Bulk Extensions
> Step 2: And Like the video. BONUS: You can also share it!

Example

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.



Got any Scala Language Question?