Skip to content

Instantly share code, notes, and snippets.

@sofoklis
Last active December 11, 2015 20:48
Show Gist options
  • Save sofoklis/4657783 to your computer and use it in GitHub Desktop.
Save sofoklis/4657783 to your computer and use it in GitHub Desktop.
partialfunctionsorelse
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