scalapattern-matching

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?


Solution

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