Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 979
egervari Avatar asked May 10 '10 04:05

egervari


1 Answers

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
like image 144
michael.kebe Avatar answered Sep 28 '22 06:09

michael.kebe