Case Classes and Pattern Matching

Case Classes can be seen as plain and immutable data-holding objects that should exclusively depend on their constructor arguments.
  • Case classes can be pattern matched
  • Case classes automatically define hashcode and equals
  • Case classes automatically define getter methods for the constructor arguments
For example:
def describe(x: Any) = x match {
     case 5 => "five"
     case true => "truth"
     case "hello" => "hi!"
     case Nil => "the empty list"
     case _ => "something else"
Sequence patterns
You can match against sequence types like List or Array just like you match against case classes:
expr match {
     case List(0, _, _) => println("found it”) //change this to List(0, _*) if you don’t want to specify how long it should be
     case _ =>
Typed patterns
You can use a typed pattern as a convenient replacement for type tests and type casts:
def generalSize(x: Any) = x match {
     case s: String => s.length
     case m: Map[_, _] => m.size
     case _ => -1
Patterns in for expressions
for ((country, city) <- capitals)
     println("The capital of "+ country +" is "+ city)