模式匹配元組

鑑於以下 List 元組:

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

模式匹配可用於以不同方式處理每個元素:

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")
  }
}

第一種情況顯示如何匹配特定字串並獲得相應的價格。第二種情況顯示使用 if 和元組提取來匹配元組的元素。