Scala - complex conditional pattern matching

25,866

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 => ... 
}
Share:
25,866
Dominic Bou-Samra
Author by

Dominic Bou-Samra

Updated on January 26, 2020

Comments

  • Dominic Bou-Samra
    Dominic Bou-Samra over 4 years

    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?

  • Rex Kerr
    Rex Kerr almost 13 years
    This doesn't actually match what the OP wrote. The control flow is different; on x>y&&z, the OP executes doSomething(), return doSomethingElseEntirely(), while yours returns doSomething() alone.
  • Tomas Petricek
    Tomas Petricek almost 13 years
    @Rex - Good point, thanks. I didn't quite get it because OP's code is missing some opening and closing curly braces. Anyway, it should be easy to fix the body accordingly.
  • Alexander Aleksandrovič Klimov
    Alexander Aleksandrovič Klimov over 10 years
    To me, this doesn't make it clear the x > y test is common to the first two branches. There's nothing inherently wrong with if/then/else and in this case, it's clearer (IMO).
  • Vincenzo Maggio
    Vincenzo Maggio over 10 years
    @Paul I agree, but it was the OP to ask for this kind of solution! :)
  • Valentin Tihomirov
    Valentin Tihomirov over 8 years
    I fail to use guards in the exception handling
  • Geoffrey Wiseman
    Geoffrey Wiseman about 7 years
    I know this is old, but I will say that in some ways I prefer the pattern match -- it lays out that there are three paths and that the paths each have a set of necessary conditions. It emphasizes the branch rather than the common elements of the conditions, which in some cases might be clearer.