Back
Close

Introduction to Scala Part3: Option & Pattern Matching

Bubu
4,004 views

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
Create your playground on Tech.io
This playground was created on Tech.io, our hands-on, knowledge-sharing platform for developers.
Go to tech.io