I'm confused about switch guards, specifically the 'when' keyword. I've seen them work with pattern matching, like in this example:
switch (obj) {
String s when s.isEmpty() -> { }
}
However, when I try to use 'when' with an enum, like so:
switch (direction) {
Up when x == 4 -> {}
}, it doesn't seem to work. I can't find any examples in the JEP either, so I wonder if this isn't supported at all. If that's the case, are there plans to support it in the future? (I updated my example to clarify the usage of the 'when' clause).
5 Answers
In theory, you could find workarounds, but typically you don’t need 'when' for enum switches. For instance, just doing:
switch(direction) {
case Up -> doSomething();
case Down -> doAnotherSomething();
}
works just fine! If you're looking to select over a numeric value instead, then you can use that 'when' syntax appropriately.
It seems like you're trying to use switch guards in a context that could get a bit messy. Do you have a specific situation in which you'd need 'when' with an enum without causing side effects?
Currently, switch guards only seem to work with pattern matching, not with enums. That 'when' syntax was likely designed with potential future expansions in mind, though! So who knows?
You might be able to get it to work by qualifying the enum constant with the enum class name. If you do that, you can use enum constants in pattern matching switches. Give that a shot!
What's the use case for using 'when' like that with enums? If you're just checking for true or false, a simple if statement might be more efficient. Enums are pretty rigid, so you usually don't need that complexity. Just keep chaining valid values!
Related Questions
Set Wordpress Featured Image Using Javascript
How To Fix PHP Random Being The Same
Why no WebP Support with Wordpress
Replace Wordpress Cron With Linux Cron
Customize Yoast Canonical URL Programmatically
[Centos] Delete All Files And Folders That Contain a String