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

ege*_*ari 5 design-patterns scala matching

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

myApi {
    case Whatever() => // code for case 1
    case SomethingElse() => // code for case 2
}
Run Code Online (Sandbox Code Playgroud)

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

mic*_*ebe 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
Run Code Online (Sandbox Code Playgroud)