Do switch guards work with enum switches?

0
3
Asked By CuriousCoder42 On

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

Answered By CodeCrafter88 On

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.

Answered By CritiqueChamp On

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?

Answered By TechieTom69 On

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?

Answered By EnumExpert77 On

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!

Answered By LogicalLeo On

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

LEAVE A REPLY

Please enter your comment!
Please enter your name here

This site uses Akismet to reduce spam. Learn how your comment data is processed.