Groovy's Elvis and Safe-Navigation Operator in Java 7
Both operators are implemented in Groovy to shorten the code.
The Elvis Operator shorten your if-conditions. You know the common ternary expression:
def gender = user.male ? "male": "female"
This you can shorten with the Elvis operator:
def gender = user.male ?: "female"
Only if the expression evaluates to false or null the default value (here: female) will be used.
The other operator is the Safe-Navigation Operator. If you are working with Java Beans and their getter methods you have often a chain of calls:
customer.getAddress().getCity();
This works fine until one of the getters return null. Then you get a NullPointerException. To avoid this you can surround this call with a try-catch block:
try{
customer.getAddress().getCity();
}catch (NullPointerException npe){
//what can I do here???
}
This are at least 5 lines of code for catching the NullPointerException. But what can you do with this exception? Commonly you do nothing. You can log this or redirect this exception to the next tier. In Groovy there is the Safe-Navigation Operator:
customer?.address?.city
At first in Groovy you can use the properties instead of accessing the getter methods. The ?. operator checks if the expression on the left hand is null. If true the complete expession evaluates to null.
For this both operators there is an proposal for a change in the Java Programming language. For now this proposal is not accepted…but we hope so
