模式匹配元组

鉴于以下 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 和元组提取来匹配元组的元素。