Partial functions

In the previous chapter, we looked at partially applied functions. We left one or more arguments unspecified, and as a result, we got another function. There are partially applied functions and there are partial functions. So, what do we mean by the term partial functions? It simply means that such a function is not defined for some values. Let's try the following example of a partial function:

scala> val f = (x: Int, y: Int) => x / y
f: (Int, Int) => Int = <function2>

scala> f(12, 3)
res0: Int = 4

scala> f(12, 0)
java.lang.ArithmeticException: / by zero
  at $anonfun$1.apply$mcIII$sp(<console>:10)
  ... 33 elided

Here, we have a function that takes two integer parameters, x and y. It divides x by y. When we pass 0 as the value ...

Get Scala Functional Programming Patterns 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.