Elvis operator

Alex Buckley Alex.Buckley at Sun.COM
Thu Jul 16 17:43:27 PDT 2009


Reinier Zwitserloot wrote:
> You couldn't use ?. for any method that returned a primitive type 

> For example, when the LHS being null is an unexpected possibility, using 
> ?. just moves the problem forward time a little bit; things are very 
> likely going to go wrong soon anyway. However, when they go wrong, they 
> either go wrong without throwing an exception, making it harder to 
> figure out there's a problem, and if you do get an exception, the 
> methods mentioned in the stack trace are now even less related to the 
> source of the problem.

These are exactly the reasons why I'm not a fan of ?. for Java.

Dierk actually wrote to me directly and explained how idiomatic Groovy 
code has a role for . and a role for ?. - I hope he will not mind me 
quoting a little: "If m is a Map, then in Groovy you can refer to the 
value of key "k" in m as  m.k  and since that returns null for unknown 
keys, you often find Elvis as  m.k?.foo()  in those usages ... you 
_don't_ write  m?.k?.foo()  because if m == null you have an ultimate 
programming error and want NPE to be thrown."

(BTW, saying 'LHS' is a bit confusing because LHS typically alludes to 
the assignment (or method invocation) context ... saying 'receiver' 
isn't quite right either, since the expression may not be a method 
invocation ... 'Primary' is probably best, see JLS 15.8.)

Alex



More information about the coin-dev mailing list