Saturday 3 January 2015

Pattern Matching in Match Expressions

Different Patterns:

1. Constant patterns

A constant pattern can only match itself.
case 0 => "zero"

2. Variable patterns

a variable pattern matches any object just like the _ wildcard character.
case foo => s"Hmm, you gave me a $foo"

3.  Constructor patterns
The constructor pattern lets you match a constructor in a case statement.
case Person(first, "Alexander") => s"An Alexander, first name = $first"

4. Sequence patterns
Use the _ character to stand for one element in the sequence, and use _* to stand for “zero or more elements”
case List(1, _*) => "a list beginning with 1, having any number of elements"

5. Tuple patterns
match tuple patterns and access the value of each element in the tuple. Use the _ wildcard if you’re not interested in the value of an element:
case (a, b, c, _) => s"4-elem tuple: got $a, $b, and $c"

6. Type patterns
list is the pattern variable, which can be accessed in the expression.
case list: List[_] => s"thanks for the List: $list"

7. Class patterns



trait Animal
case class Dog(name: String) extends Animal
case class Cat(name: String) extends Animal

  def determineType(x: Animal): String = x match {
    case Dog(moniker) => "Got a Dog, name = " + moniker
    case _:Cat => "Got a Cat (ignoring the name)"
    case _ => "That was something else"
  }


No comments:

Post a Comment