Skip to content

Instantly share code, notes, and snippets.

@loicdescotte
Last active December 23, 2015 20:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save loicdescotte/6691349 to your computer and use it in GitHub Desktop.
Save loicdescotte/6691349 to your computer and use it in GitHub Desktop.
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
  }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment