Issue Details (XML | Word | Printable)

Key: GROOVY-2157
Type: Bug Bug
Status: Closed Closed
Resolution: Fixed
Priority: Major Major
Assignee: Jochen Theodorou
Reporter: BarzilaiSpinak
Votes: 0
Watchers: 0
Operations

If you were logged in you would be able to see more operations.
groovy

Elvis operator is evaluating the "true" expression twice

Created: 30/Sep/07 11:31 AM   Updated: 30/Sep/07 02:33 PM   Resolved: 30/Sep/07 02:33 PM
Return to search
Component/s: lexer, parser, syntax
Affects Version/s: 1.1-beta-3
Fix Version/s: 1.1-rc-1

Time Tracking:
Not Specified


 Description  « Hide

From the mailing list:

On 9/30/07, Jörg Staudemeyer wrote:
> > groovy> def myMethod() { println "called"; "result" }
> > groovy> myMethod() ?: "default"
> > groovy> go
> > called
> > called
> > ===> result

On 9/30/07, Charles Oliver Nutter wrote:
> class Foo {
> int count = 1
> def myMethod() { count += 1; count }
> }
>
> println (new Foo().myMethod ?: "no count")
>
> ?: shouldn't call the condition twice since that could lead to
> unfortunate side effects.

And barspi says:

To me it looks more like a quick and dirty implementation (for the beta3 release), which could have side effects as Charles mentioned.
In the best case, the side effect would be an "unnecessary" performance hit by evaluating twice.
The idea of the elvis operator was twofold: a) syntactic sugar b) efficiency

Actually, this behaviour is more dangerous than using the full syntax of the ternary operator. When you use the whole expr ? expr : expr2, you are explicitly stating (and visually seeing) that you are evaluating expr twice (possibly invoking some embedded methods twice).

If you have to think about hidden semantics, all the groovy and sugary effect is lost



Jochen Theodorou added a comment - 30/Sep/07 02:24 PM

changed to the new specification in this report