如何在scala中编写匹配代码块的模式?

时间:2010-05-10 04:53:49

标签: scala design-patterns matching

如何将包含代码块的函数编码为包含case语句的参数?例如,在我的代码块中,我不想明确地进行匹配或默认情况。我看起来像这样

myApi {
    case Whatever() => // code for case 1
    case SomethingElse() => // code for case 2
}

在我的myApi()中,它实际上会执行代码块并进行匹配。

2 个答案:

答案 0 :(得分:6)

您必须使用PartialFunction

scala> def patternMatchWithPartialFunction(x: Any)(f: PartialFunction[Any, Unit]) = f(x)
patternMatchWithPartialFunction: (x: Any)(f: PartialFunction[Any,Unit])Unit

scala> patternMatchWithPartialFunction("hello") {
     |   case s: String => println("Found a string with value: " + s)
     |   case _ => println("Found something else")
     | }
Found a string with value: hello

scala> patternMatchWithPartialFunction(42) {
     |   case s: String => println("Found a string with value: " + s)
     |   case _ => println("Found something else")
     | }
Found something else

答案 1 :(得分:-1)

这应该足以解释它:A Tour of Scala: Pattern Matching