1

Groovy allows me to say

x?.getY()

instead of the verbose

x == null ? null : x.getY().

Java does not allow custom operators, but I can imagine a utility method that's used like so:

safe(x).getY();

Is there any standard library in the world's Maven repos that does this kind of thing? If no, and I wanted to include it in an open source library (like apache.commons.lang), where would it best fit?

Edit: sample implementation of safe():

public static <T> T safe(T x) {
    if (x==null) {
        return new NullReturningMock<T>();
    } else {
        return x;
    }
}
Anthony Accioly
  • 21,918
  • 9
  • 70
  • 118
Robert Jack Will
  • 10,333
  • 1
  • 21
  • 29
  • Ewwwwww. That'd inevitably require (slow) reflection. Do it the old-fashioned way, please. – Louis Wasserman Feb 02 '12 at 20:08
  • @LouisWasserman Not necessarily, you could also proxy concrete classes using something like CGLIB. (Overkill, with lots of bug-prone code, but faster!) – millimoose Feb 02 '12 at 20:17

1 Answers1

2

Not exactly what you were asking for but as a Java programmer that spent some time coding in Scala I can recommend Google Guava's implementation of Optional.
Elvis and Safe Operator Proposal didn't make it to Java 7, maybe for 8. This question may be an interesting read.

Update 2023: Still no Elvis Operator in Java, but Optional has been part of the Standard Library since Java 8.

Anthony Accioly
  • 21,918
  • 9
  • 70
  • 118