Partial functions do not suffice for every input given, which means these are defined to serve a purpose for a specific set of input parameters. To understand more, let's first define a partial function:
scala> val oneToFirst: PartialFunction[Int, String] = { | case 1 => "First" | } oneToFirst: PartialFunction[Int, String] = <function1> scala> println(oneToFirst(1)) First
In the preceding code, we defined a partial function named oneToFirst
. We also specified type parameters for our partial function; in our case we passed Int
, String
. The PartialFunction
function is a trait in Scala, defined as:
trait PartialFunction[-A, +B] extends (A) => B
The trait as shown expects two parameters A
and B
, that become the input and output types of our partial function. Our oneToFirst
partial function simply expects 1
and returns a string representation for 1 as first. That's why when we try to call the function by passing 1, it works fine; but if we try...