Fwd: Elvis operator

Dierk König dierk.koenig at canoo.com
Fri Jul 17 00:31:40 PDT 2009


for everybodies information

> Von: Dierk König <dierk.koenig at canoo.com>
> Datum: 16. Juli 2009 22:32:04 GMT+02:00
> An: Alex Buckley <Alex.Buckley at Sun.COM>
> Betreff: Re: Elvis operator
>
> Hi Alex,
>
> thanks a lot for your insight and questions.
>
>> Putting ?: and ?. side-by-side shows they are dual in a type- 
>> theoretic
>> sense. ?: returns a specific value of a specific type (indicating a
>> default), while ?. returns a non-value of the bottom type.
>> Since the
>> bottom type is a subtype of all other types, the non-value will  
>> swallow
>> all messages sent to it. The non-value turns into the null  
>> reference at
>> assignment conversion or method invocation conversion, of course.
>
> Well, from the effect you are describing, I don't quite see the  
> "duality".
>
> However, even assuming it is there, it would still be no good reason
> to also call ?. Elvis. It would only be confusing.
> Call it Jacko, if you will (but then I would write the operator /. to
> indicate the tilted hat that only reveals one eye).
>
>> Turning to more practical matters, do you have a sense of how  
>> often ?.
>> is used in Groovy code?
>
> There are places, where it is often used, e.g. in GSPs (Groovy  
> Server Pages
> as used in Grails). This is a special case of access to Maps as the  
> model
> that is given from the controller to the view is a Map.
> 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.
>
>> Why would anyone dereference with '.' when they
>> could use '?.' ?
>
> because you often want NPE to be thrown for the sake of failing early.
> In the example above, you _don't_ write
>  m?.k?.foo()
> because if m == null you have an ultimate programming error and want
> NPE to be thrown.
>
>> If '.' is still commonly used, is Groovy code littered
>> with as many == comparisons with null as Java code is?
>
> Not at all. Groovy idiomatic code has very few null checks.
> The exceptional case where you need those has to do with
> the Groovy truth. You sometimes want to distinguish e.g. between
> a String being null and a String being empty.
>
> cheers
> Dierk
>
>




More information about the coin-dev mailing list