9.4 类型和卫述句的匹配

有时,我们要处理的序列,其值可能具有不同的类型。比方说,我们对Int序列的处理方式也许不同于对Double序列的处理方式。在Scala里,case语句可以根据类型进行匹配。

PatternMatching/MatchTypes.scala

  1. Line 1 def process(input: Any) {
  2. - input match {
  3. - case (a: Int, b: Int) => print("Processing (int, int)... ")
  4. - case (a: Double, b: Double) => print("Processing (double, double)... ")
  5. 5 case msg : Int if (msg > 1000000) => println("Processing int > 1000000")
  6. - case msg : Int => print("Processing int... ")
  7. - case msg: String => println("Processing string... ")
  8. - case _ => printf("Can't handle %s... ", input)
  9. - }
  10. 10 }
  11. -
  12. - process((34.2, -159.3))
  13. - process(0)
  14. - process(1000001)
  15. 15 process(2.2)

这里,我们见识到了在case里如何为单一的值和元组元素指定类型。除了类型之外,还可以使用卫述句(guard)。卫述句用if从句表示,在模式匹配里,对表达式求值前必须满足卫述句。

case的顺序很重要。Scala会自上而下地求值。所以,上面代码5和6两行是不能交换的。上面代码的输出如下:

  1. Processing (double, double)... Processing int... Processing int > 1000000
  2. Can't handle 2.2...