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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With