Question

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.

Was it helpful?

Solution

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

OTHER TIPS

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

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top