Last active
May 18, 2020 14:05
-
-
Save fancellu/9bf392e79daa929f8c22ccf7fd25d0c1 to your computer and use it in GitHub Desktop.
Simple example of custom extractor objects vs existing case class extractors
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
is dino | |
14 | |
no one | |
is dino | |
14 | |
no one |
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
object Unapp extends App { | |
case class MyClass(age: Int, name: String) | |
private object Age { | |
def unapply(myClass: MyClass): Option[Int] = myClass match { | |
case MyClass(age, _) if (age > 0) => Option(age) | |
case _ => None | |
} | |
} | |
private object Name { | |
def unapply(myClass: MyClass): Option[String] = myClass match { | |
case MyClass(_, name) => Option(name) | |
case _ => None | |
} | |
} | |
private object Dino { | |
def unapply(myClass: MyClass): Boolean = myClass match { | |
case MyClass(53, "Dino") => true | |
case _ => false | |
} | |
} | |
val matchMe: MyClass => Unit = { | |
case Dino() => println("is dino") | |
case Age(age: Int) => println(age) | |
case Name(name: String) => println(name) | |
} | |
matchMe(MyClass(53, "Dino")) | |
matchMe(MyClass(14, "Neo")) | |
matchMe(MyClass(0, "no one")) | |
// without the above custom extractor objects | |
val matchMe2: MyClass => Unit = { | |
case MyClass(53, "Dino") => println("is dino") | |
case MyClass(age, _) if (age > 0) => println(age) | |
case MyClass(_, name) => println(name) | |
} | |
matchMe2(MyClass(53, "Dino")) | |
matchMe2(MyClass(14, "Neo")) | |
matchMe2(MyClass(0, "no one")) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment