Dominic Bou-Samra
Dominic Bou-Samra

Reputation: 15406

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?

Upvotes: 19

Views: 28366

Answers (1)

Tomas Petricek
Tomas Petricek

Reputation: 243041

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 => ... 
}

Upvotes: 48

Related Questions