I recently came across the discussion around the Java proposal for using primitive types like boolean in switch statements and I'm a bit bummed it's not making it into OpenJDK 25. I was hoping to simplify my code with this feature since Java doesn't have a solid conditional expression construct as seen in C#, Kotlin, or Dart. My plan was to use a switch construct like this:
```java
var res = switch (predicate) {
case true -> doIfTrueAndReturn();
case false -> doIfFalseAndReturn();
};
```
Seems like it could be a great solution! What are your thoughts on this?
5 Answers
I think the Java team tends to be cautious with new features, and it makes sense—especially when they're laying down the groundwork for future enhancements. They know what they're doing, even if it seems like a long wait!
That example you gave seems a bit odd. Isn’t it just a verbose way of doing this?
```java
var res = predicate ? doIfTrue() : doIfFalse();
```
True, it’s another way to do it. But readability often suffers with nested ternary operators, whereas switch statements can be clearer, especially for complex conditions.
I didn't read the JEP, but your example feels forced. If a language supports a feature like if expressions, it shouldn't be awkwardly jammed into switch statements like this.
That’s fair! But remember this switch for booleans is a step towards future enhancements. It all adds up to making the language more robust with time.
Just curious, why would you even want to use a primitive boolean in a switch statement? It feels like it complicates things for what could be done simply with an if statement.
Good question! Using switch over booleans actually makes the code more readable in some cases, especially when you consider a more complex structure. It’s about unifying the language and simplifying developer workload.
Three preview releases without any change seems really excessive. It would be nice if they provided a clearer reason for the delay. It feels like they’re just dragging their feet a bit.
Right? There are so many moving parts with Java updates; it's tough to keep track of what's happening. But I believe they're trying to avoid locking themselves into a problematic situation.
I totally get that! They have to ensure everything is stable before moving forward. Better safe than sorry!