Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/scala/19.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/design-patterns/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何在scala中编写模式匹配代码块?_Scala_Design Patterns_Matching - Fatal编程技术网

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

如何在scala中编写模式匹配代码块?,scala,design-patterns,matching,Scala,Design Patterns,Matching,如何编写一个函数,将一个代码块作为包含case语句的参数?例如,在我的代码块中,我不想显式地进行匹配或默认情况。我看起来像这样 myApi { case Whatever() => // code for case 1 case SomethingElse() => // code for case 2 } 在myApi()内部,它将实际执行代码块并进行匹配。这应该足以解释它:您必须为此使用部分函数 scala> def patternMatchWithPar

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

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

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

这应该足以解释它:

您必须为此使用
部分函数

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

不,我知道如何进行模式匹配。。。我想做一个函数,它接受一个只包含case语句的代码块。。。然后让该函数在内部处理匹配。基本上,对于普通代码块,我们有一个带(=>Unit)的参数,但对于模式匹配则不同。我基本上想对常规代码块做同样的事情,但是对case语句做同样的事情。谢谢!我知道这有点奇怪,但我找不到这样的例子。@egervari同样的模式也适用于
Function1
。带有
case
语句的块是函数文本,可以同时代表
PartialFunction
Function1
,具体取决于预期的类型。