Scala Language Pattern Matching Pattern Matching on tuples


Example

Given the following List of tuples:

val pastries = List(("Chocolate Cupcake", 2.50), 
                    ("Vanilla Cupcake", 2.25),
                    ("Plain Muffin", 3.25))

Pattern matching can be used to handle each element differently:

pastries foreach { pastry =>
  pastry match {
    case ("Plain Muffin", price) => println(s"Buying muffin for $price")
    case p if p._1 contains "Cupcake" => println(s"Buying cupcake for ${p._2}")
    case _ => println("We don't sell that pastry")
  }
}

The first case shows how to match against a specific string and get the corresponding price. The second case shows a use of if and tuple extraction to match against elements of the tuple.