Fork me on GitHub

Graceless Failures

Tips, tricks, missteps, and minor revelations on the path to Scala wisdom.

Pattern Matching and Extraction

Pattern matching is cool:

val lst = List(1,2,3,4)

lst match {
  case 1 :: _ => // match anything with the first element as 1
}

lst match {
  case _ :: 2 :: _ => // match anything with the second element as 2
}

But it gets fun, because you can “extract” values (put them out) and match at the same time:

lst match {
  case first :: 2 :: _ => // matches if the second item in the list is 2 and assigns the first element to "first"
}