switch statements with empty parameters parameters

mirage newblood17 at gmail.com
Tue Oct 1 13:09:43 UTC 2024


Hello.

In the recent years switch has been enhanced and there are some discussions
about enhancing it even further with try - catch evaluation style inside
the switch itself.

i was wondering if an additional enhancement could be to be able to use an
empty parameter switch so we can use switch as a general-purpose
replacement of if-else chains. Switch has many advantages over if-else
chains, being these the most relevant.

- The code it's cleaner and more readable, even with nested switch
expressions.
- Switch can be an expression, so it can return an assign a value to a
variable.

nowadays we can use something like this.

var i = someIntMethodParameter;
var j = someStringMethodParameter
var res = switch (new Object()){
    case Object _ when i < 5 -> 5;
    case Object _ when i > 10 -> 10;
    case Object _ when j.length() < 10 -> 20;
    case null -> 0;
    default -> throw new IllegalStateException("Unexpected value: " + new
Object());
};

as we can see here this is effectively a replacement for if-else chains
that returns the first true case, but there are some problems with this
syntax and semantics

. I was wondering if it could be a good idea to

*
};*
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://mail.openjdk.org/pipermail/amber-dev/attachments/20241001/9afae049/attachment.htm>


More information about the amber-dev mailing list