Last active
December 11, 2015 20:48
-
-
Save sofoklis/4657783 to your computer and use it in GitHub Desktop.
partialfunctionsorelse
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 positivePF: PartialFunction[Int, String] = { case i if i > 0 => "Positive"} | |
| //> positivePF : PartialFunction[Int,String] = <function1> | |
| val negativePF: PartialFunction[Int, String] = { case i if i < 0 => "Negative"} | |
| //> negativePF : PartialFunction[Int,String] = <function1> | |
| val zeroPF: PartialFunction[Int, String] = { case 0 => "Zero"} | |
| //> zeroPF : PartialFunction[Int,String] = <function1> | |
| // combine the indivitual partial functions to form one that covers all of them | |
| val number = positivePF orElse negativePF orElse zeroPF | |
| //> number : PartialFunction[Int,String] = <function1> | |
| number(0) //> res10: String = Zero | |
| number(1) //> res11: String = Positive | |
| number(-1) //> res12: String = Negative | |
| // which is equivalent to a case statement that is composed out of | |
| // the case statements that created the individual partial functions | |
| val numberPF: PartialFunction[Int, String] = { | |
| case i if i > 0 => "Positive" | |
| case i if i < 0 => "Negative" | |
| case 0 => "Zero" | |
| } //> numberPF : PartialFunction[Int,String] = <function1> | |
| numberPF(0) //> res13: String = Zero | |
| numberPF(1) //> res14: String = Positive | |
| numberPF(-1) //> res15: String = Negative | |
| // and here with full match statement, the only difference is that this one is a regular function | |
| def numberF(x: Int): String = x match { | |
| case i if i > 0 => "Positive" | |
| case i if i < 0 => "Negative" | |
| case 0 => "Zero" | |
| } //> numberF: (x: Int)String | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment