Created
August 1, 2017 13:39
-
-
Save waleedsamy/ffdaa08cbca2d47fdaffcfc147769998 to your computer and use it in GitHub Desktop.
Function and PartialFunction Scala classes
This file contains 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
// 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) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
http://blog.bruchez.name/2011/10/scala-partial-functions-without-phd.html
https://blog.matthewrathbone.com/2017/03/06/scala-object-apply-functions.html