20

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?

0

1 Answer 1

49

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 => ... 
}
Sign up to request clarification or add additional context in comments.

6 Comments

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.
@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.
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).
@Paul I agree, but it was the OP to ask for this kind of solution! :)
I fail to use guards in the exception handling
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.