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?
Pattern matching is the second most widely used feature of Scala, after function values and closures. Scala provides great support for pattern matching, in processing the messages. A pattern match includes a sequence of alternatives, each starting with the keyword case.
Pattern matching is a mechanism for checking a value against a pattern. A successful match can also deconstruct a value into its constituent parts. It is a more powerful version of the switch statement in Java and it can likewise be used in place of a series of if/else statements.
case _ => does not check for the type, so it would match anything (similar to default in Java). case _ : ByteType matches only an instance of ByteType . It is the same like case x : ByteType , just without binding the casted matched object to a name x .
Pattern matching tests whether a given value (or sequence of values) has the shape defined by a pattern, and, if it does, binds the variables in the pattern to the corresponding components of the value (or sequence of values). The same variable name may not be bound more than once in a pattern.
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 => ...
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With