Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scala - complex conditional pattern matching

I have a statement I want to express, that in C pseudo-code would look like this:

switch(foo):
    case(1)
        if(x > y) {
            if (z == true)
                doSomething()
            }
            else {
                doSomethingElse()
            }
        return doSomethingElseEntirely()

    case(2)
        essentially more of the same

Is a nice way possible with the scala pattern matching syntax?

like image 391
Dominic Bou-Samra Avatar asked Jul 24 '11 00:07

Dominic Bou-Samra


People also ask

Does Scala have pattern matching?

Pattern matching is the second most widely used feature of Scala, after function values and closures. Scala provides great support for pattern matching, in processing the messages. A pattern match includes a sequence of alternatives, each starting with the keyword case.

How does Scala pattern matching work?

Pattern matching is a mechanism for checking a value against a pattern. A successful match can also deconstruct a value into its constituent parts. It is a more powerful version of the switch statement in Java and it can likewise be used in place of a series of if/else statements.

What is case _ in Scala?

case _ => does not check for the type, so it would match anything (similar to default in Java). case _ : ByteType matches only an instance of ByteType . It is the same like case x : ByteType , just without binding the casted matched object to a name x .

How pattern matching works in a function's parameter list?

Pattern matching tests whether a given value (or sequence of values) has the shape defined by a pattern, and, if it does, binds the variables in the pattern to the corresponding components of the value (or sequence of values). The same variable name may not be bound more than once in a pattern.


1 Answers

If you want to handle multiple conditions in a single match statement, you can also use guards that allow you to specify additional conditions for a case:

foo match {    
  case 1 if x > y && z => doSomething()
  case 1 if x > y => doSomethingElse()
  case 1 => doSomethingElseEntirely()
  case 2 => ... 
}
like image 84
Tomas Petricek Avatar answered Oct 25 '22 19:10

Tomas Petricek