Introduction to Scala Part3: Option & Pattern Matching

Bubu
4,052 views

Open Source Your Knowledge, Become a Contributor

Technology knowledge has to be shared and made accessible for free. Join the movement.

Create Content

Pattern Matching

Pattern matching is a generalization of switch from C/Java to class hierarchies. It’s expressed in Scala using the keyword match.

Examples:

def eval(e: Expr): Int = e match {
    case Number(n) => n
    case Sum(e1, e2) => eval(e1) + eval(e2)
}

Rules

  • Match is followed by a sequence of cases
  • Each case associates an expression to a pattern
  • An exception MatchError is thrown if no pattern matches the value of the selector

Pattern forms

Patterns are constructed from:

  • Constructors : Number, Sum, etc.
  • Variables : n, e1, e2, etc.
  • Wildcard patterns : _
  • Constants : 1 , true

Variables always begin with a lowercase letter. The same variable name can only appear once in a pattern (Sum(x, x) is not a legal pattern)

Constructors and the names of constants begin with a capital letter, with the exception of the reserved words: null, true ,false

headOption
sum
multiply
fibonacci
lastOption
Open Source Your Knowledge: become a Contributor and help others learn. Create New Content