你如何编写了Scala的模式匹配代码块?
-
25-09-2019 - |
题
你如何编写一个函数中的代码块花费为包含case语句的参数?举例来说,在我的代码块,我不想做一个匹配或默认情况下明确。我期待这样的事情
myApi {
case Whatever() => // code for case 1
case SomethingElse() => // code for case 2
}
和我myApi()内,它会实际执行的代码块,做匹配。
解决方案
您必须使用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
其他提示
此应该足以解释: Scala中的游:模式匹配
不隶属于 StackOverflow