Partially defined functions

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

Get Scala Design Patterns - Second Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.