Uncategorized

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)

 

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s