开发者

How do you code up a pattern matching code block in scala?

开发者 https://www.devze.com 2022-12-30 04:57 出处:网络
How do you code a function that takes in a block of code as a parameter that contains case statements? For instance, in my block of code, I don\'t want to do a match or a default case explicitly. I am

How do you code a function that takes in a block of code as a parameter that contains case statements? For instance, in my block of code, I don't want to do a match or a default case explicitly. I am looking something like this

myApi {
    case Whatever() => // code for case 1
    case SomethingElse开发者_运维百科() => // code for case 2
}

And inside of my myApi(), it'll actually execute the code block and do the matches.


You have to use a PartialFunction for this.

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


This should suffice to explain it: A Tour of Scala: Pattern Matching

0

精彩评论

暂无评论...
验证码 换一张
取 消