Created
February 6, 2017 01:08
-
-
Save DmitryBe/688ee36b4ec8ca636ee15f44b467bbb6 to your computer and use it in GitHub Desktop.
Scala: Combine several partial functions into one
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
val a: PartialFunction[String, Int] = { case "a" => 1 } | |
val b: PartialFunction[String, Int] = { case "b" => 2 } | |
val c: PartialFunction[String, Int] = { case "c" => 3 } | |
val ab = a orElse b // combine functions a and b | |
ab("a") // 1 | |
ab("b") // 2 | |
ab("c") // MatchError | |
val abc = (a :: b :: c :: Nil) reduceLeft (_ orElse _) // combine list of functions | |
abc("a") // 1 | |
abc("b") // 2 | |
abc("c") // 3 | |
abc("d") // MatchError | |
// Order is important | |
val f1: PartialFunction[Int, Int] = { case 1 => 10 } | |
val f2: PartialFunction[Int, Int] = { case 1 => 20 } | |
val f12 = f1 orElse f2 | |
val f21 = f2 orElse f1 | |
f12(1) // 10 | |
f21(1) // 20 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment