PartialFunction composition in Scala REPL

Following is a PartialFunction composition in Scala REPL:

$ scala

Welcome to Scala 2.11.8 (Java HotSpot(TM) 64-Bit Server VM, Java 1.8.0_77). Type in expressions for evaluation. Or try :help. scala>val even:PartialFunction[Int, String] = {

| case i if i%2 == 0 => "even"

| }

even: PartialFunction[Int,String] = scala>

scala>val odd:PartialFunction[Int, String] = { case _ => "odd"}

odd: PartialFunction[Int,String] =

scala>

scala>val evenOrOdd:(Int => String) = even orElse odd

evenOrOdd: Int => String =

scala>

scala>println( evenOrOdd(1) == "odd" ) true

scala>println( evenOrOdd(2) == "even" )

true

scala>

Scala allows us to compose as many PartialFunctions as we want. PartialFunction composition happens with the orElse function. In the preceding code, we defined an immutable variable called even, which verifies even numbers. Secondly, we created a second immutable variable called odd, which checks for odd numbers. Then we did the composition, and created a third PartialFunction called evenOrOdd with compose even and odd using the orElse operator.

 
Source