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 => ...
}
Author by
Dominic Bou-Samra
Updated on January 26, 2020Comments
-
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 almost 13 yearsThis doesn't actually match what the OP wrote. The control flow is different; on
x>y&&z
, the OP executesdoSomething()
,return doSomethingElseEntirely()
, while yours returnsdoSomething()
alone. -
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 over 10 yearsTo 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 over 10 years@Paul I agree, but it was the OP to ask for this kind of solution! :)
-
Valentin Tihomirov over 8 yearsI fail to use guards in the exception handling
-
Geoffrey Wiseman about 7 yearsI 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.