loicdescotte
9/24/2013 - 9:14 PM

Scala pattern matching examples

Scala pattern matching examples

Scala pattern matching example

Value matching

def f(x: Int): String = x match {
  case 1 | 2 => "one or two"
  case 3 => "three"
  case _ => "other values"
}

Type matching

def f(x: Any): String = x match {
  case i: Int => "integer: " + i
  case _: Double => "a double"
  case s: String => "I want to say " + s
}

List structure matching

Note : x :: tail means a List with a first element x and a tail

def sum(xs: List[Int]): Int = {
  xs match {
    case x :: tail => x + sum(tail) // if there is an element, add it to the sum of the tail (recursive call)
    case Nil => 0 // if there are no elements, then the sum is 0
  }
}