views:

145

answers:

2

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. Help?

A: 

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

Randall Schulz
No, I know how to pattern match... I want to make a function that takes in a block of code that only consist of case statements... and then have that function process the matching internally. Basically, for normal code blocks, we have a parameter with (=> Unit), but it's different for pattern matching. I essentially want to do the same thing for regular code blocks but for case statements.
egervari
+6  A: 

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
michael.kebe
Thanks! I knew it was something weird, but I couldn't find an example of this.
egervari
@egervari the same pattern applies to `Function1` as well. Blocks with `case` statements are function literals, and can stand for both `PartialFunction` and `Function1`, depending on what the expected type is.
Daniel