Skip to content

Instantly share code, notes, and snippets.

@waleedsamy
Created August 1, 2017 13:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save waleedsamy/ffdaa08cbca2d47fdaffcfc147769998 to your computer and use it in GitHub Desktop.
Save waleedsamy/ffdaa08cbca2d47fdaffcfc147769998 to your computer and use it in GitHub Desktop.
Function and PartialFunction Scala classes
// func1 and func2 are synonyms
val func1 = (x: String) => "hello %s".format(x)
func1("world")
func1.apply("world")
val func2 = new Function1[String, String] {
def apply(x: String) = "hello %s".format(x)
}
func2("world")
func2.apply("world")
/**************************************************/
// pfunc3 and pfunc4 are synonyms
val pfunc3 = new PartialFunction[Int, Int] {
def apply(d: Int) = 42 / d
def isDefinedAt(d: Int) = d != 0
}
pfunc3.isDefinedAt(41)
func3(42)
val pfunc4: PartialFunction[Int, Int] = {
case d: Int if d != 0 ⇒ 42 / d
}
pfunc4.isDefinedAt(41)
func4(42)