5

您如何编写一个将代码块作为包含案例语句的参数的函数?例如,在我的代码块中,我不想明确地进行匹配或默认情况。我正在寻找这样的东西

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

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

4

2 回答 2

6

您必须为此使用 a 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
于 2010-05-10T06:08:05.453 回答
-1

这应该足以解释它:Scala 之旅:模式匹配

于 2010-05-10T05:03:43.660 回答