Skip to content

Instantly share code, notes, and snippets.

@shawndumas
Created May 8, 2013 15:16
Show Gist options
  • Save shawndumas/5541159 to your computer and use it in GitHub Desktop.
Save shawndumas/5541159 to your computer and use it in GitHub Desktop.
Partial Functions in Scala
val doubleEvenNumbers = new PartialFunction[Int, Int] {
def isDefinedAt(x: Int) = x % 2 == 0
def apply(v1: Int) = v1 * 2
}
val tripleOddNumbers = new PartialFunction[Int, Int] {
def isDefinedAt(x: Int) = x % 2 != 0
def apply(v1: Int) = v1 * 3
}
val doubleOrTriple = doubleEvenNumbers orElse tripleOddNumbers
doubleOrTriple(3) // => 9
doubleOrTriple(4) // => 8
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment