Scala concepts: Partial Function

A Partial Function in Scala is similar to function type `A => Option[B]` (Option Type).

The most useful aspect is PartialFunction.condOpt which allows you to reduce boilerplate when writing pattern matches (Pattern Matching).

For example, this is how it looks if you write a simple pattern match:

def getNaming(num: Int): Option[String] =
  num match {
    case 1 => Some("One")
    case _ => None
  }

assert(getNaming(1) == Some("One"))

assert(getNaming(2) == None)

And this is how it looks in the PartialFunction code:

def getNaming(num: Int): Option[String] =
  PartialFunction.condOpt(num) { case 1 => "One" }

assert(getNaming(1) == Some("One"))

assert(getNaming(2) == None)

Turning it into a complete function

def samplePf: PartialFunction[Int, String] = { case 1 => "One" }

def samplePf2: PartialFunction[Int, String] = { case 3 => "Three" }

def combinedPf: PartialFunction[Int, String] = samplePf.orElse(samplePf2)

def completeFunction: Int => Option[String] = combinedPf.lift

assert(samplePf(1) == "One")

assert(samplePf.isDefinedAt(1), "Partial function is defined at 1")

assert(!samplePf.isDefinedAt(2), "Partial function is not defined at 2")

assert(completeFunction(1) == Some("One"))

assert(completeFunction(3) == Some("Three"))

assert(completeFunction(3) == Some("Three"))

Note if the .apply method is called where it is not defined, an exception will be thrown.