April 2018
Intermediate to advanced
396 pages
11h 8m
English
We already said that partial functions are only defined for specific subsets of all possible values the functions can get. This is quite useful, as we can basically perform filter and map at once. This means fewer CPU cycles and more readable code. Let's see an example:
object PartiallyDefinedFunctions { val squareRoot: PartialFunction[Int, Double] = { case a if a >= 0 => Math.sqrt(a) }}
We defined a partial function from Int to Double. It checks whether a number is non-negative and returns the square root of that number. This partial function can be used as follows:
object PartiallyDefinedExample { import PartiallyDefinedFunctions._ def main(args: Array[String]): Unit = { val items = List(-1, 10, 11, -36, 36
Read now
Unlock full access