Add switch statement/expression with pattern matching and destructuring
jaccomoc opened this issue · 1 comments
jaccomoc commented
It would be nice to have a generic switch statement/expression to support the standard Java type switch statements as well as more functional style pattern matching with destructuring and binding variables.
Multiple matches should be able to be provided separater by commas (for simple literal comparisons).
Some examples:
switch(x) { 1,2 -> 'xyz'; 3,4,5 -> 'abc'; default => '' }
switch (x) {
[1,2,3], [4,5,6] -> println 'abc'
[] -> println 'xxx'
}
def str = switch (x) {
String -> 'x is a string
int,long,double,Decimal -> 'x is a number'
default -> "x is ${x.className()}"
}
switch (x) {
[_, 2, *] -> 'abc' // _ matches any value, * matches any number of values
[i, _, 3] -> i * i // binds i to first element in list if matches
[i, i, _] -> 2 * i // binds i to first element if first two elements of 3 element list are the same
_ -> x // same as using default since _ matches anything
}
For each matching pattern an additional expression should also be able to be provided:
switch (x) {
[_, 2, *] if x.size() > 5 => 'abc'
[i, _, 3] if i > 2 => i * i
[i, i, _] if i < 0 => 2 * i
_ if x.size() < 2 => x
}
Syntax is still being worked out.
jaccomoc commented
Code complete. See Pattern Matching and Destructuring for full description of feature.