The original idea comes from groovy. It was proposed for Java 7 as part of Project Coin: https://wiki.openjdk.java.net/display/Coin/2009+Proposals+TOC (Elvis and Other Null-Safe Operators), but hasn't been accepted yet.
The related Elvis operator ?: was proposed to make x ?: y shorthand for x != null ? x : y, especially useful when x is a complex expression.
syntax - Java "?." operator for checking null - What is it? (Not Ternary!) - Stack Overflow
How hard would it be to add a safe call operator to the Java language?
Doing null check on @Nullable functions via ternary operator still gets highlighted with "Potential null pointer access" problem
Elvis and other null-safe operators in Java
The original idea comes from groovy. It was proposed for Java 7 as part of Project Coin: https://wiki.openjdk.java.net/display/Coin/2009+Proposals+TOC (Elvis and Other Null-Safe Operators), but hasn't been accepted yet.
The related Elvis operator ?: was proposed to make x ?: y shorthand for x != null ? x : y, especially useful when x is a complex expression.
This syntax does not exist in Java, nor is it slated to be included in any of the upcoming versions that I know of.
Checking for null is quite verbose in Java. The current best practice is to either use Nullability annotations or Optional<T>. Personally, I'm in the annotations camp. Yes, optional is very useful in streams but I don't like the cognitive and runtime overhead it implies anywhere else.
My dream would be if one day nullability would be added to the type system. Obviously, that's a lot of work. But wouldn't be a pragmatic first step, to reduce just the boilerplate of null checks with a safe call operator? The compiler could surely rewrite this code:
if (getLoggedInUser()?.isPowerUser()) {
}To this:
if (getLoggedInUser() != null && getLoggedInUser().isPowerUser()) {
}To avoid an unexpected double method invocation, it could assign to ad hoc created temp variables:
User generatedSafeCall1;
if ((generatedSafeCall1 = getLoggedInUser()) != null && generatedSafeCall1.isPowerUser()) {
}
I believe this would end a lot of complaints about null handling in Java. Since only new code would use the ?. operator, backwards compatibility shouldn't be an issue either. Are there any downsides that I'm missing?