Skip to content

Instantly share code, notes, and snippets.

@ctataryn
Last active August 29, 2015 13:57
Show Gist options
  • Save ctataryn/9900598 to your computer and use it in GitHub Desktop.
Save ctataryn/9900598 to your computer and use it in GitHub Desktop.
case class Person(fname: String, lname: String)
val p = Person("Craig", "Tataryn")
p match {
case Person("Sandy", "Conner") => println("You thought I was a nurse!?!?!")
case Person("Craig", "Tataryn") => println("Hello handsome!")
case Person("Mayumi", "Liyanage") => println("Hello beautiful!")
case Person("Craig", _) => println("Great Name!")
}
Output:
>>> Hello handsome!
What's really happening? A few things. Adding "case" to the to the Person class declaration causes
some special boiler plate to be added to the class.
Two properties are created named fname and lname, they are read only via p.fname p.lname, if you want
them to be writeable add "var" in front of each like so:
case class Person(var fname: String, var lname: String)
a "companion object" named Person is created with the following method:
object Person {
def apply(fname:String, lname:String): Person = {
new Person(fname, lname)
}
}
The reason the keyword chosen to add all this boiler plate code is called "case" is the fact that
after using the "case"keyword on an class declartion, the class can be used in a case statement
like so:
p match {
case Person("Craig", "Tataryn") => ...
}
What scala did was it added an "unapply" method to your Person class like so:
def unapply(): (String, String) = {
(this.fname, this.lname)
}
Then Scala is actually compared ("Craig", "Tataryn") from the case statement to the result of
invoking p.unapply(), which in my example way up above would also be ("Craig", "Tataryn")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment