/ totd

TOTD: Scala - Partial Functions

When matching over an object, every case is merely a function1. To be precise, each case is a PartialFunction.

// fn1: PartialFunction[Int,String] = <function1>

val fn2: PartialFunction[Int, String] = { case n: Int => (n * 2).toString }
// fn2: PartialFunction[Int,String] = <function1>

// We now have two partial functions that can be chained with the orElse combinator 
(fn1 orElse fn2)(2) // 4
(fn1 orElse fn2)(6) // 6

The compiler allows us to do stuff like this while using sugared up syntax like this:

  case n: Int if n > 5 => n.toString
  case n: Int => (n * 2).toString
}```