Uploaded image for project: 'Groovy'
  1. Groovy
  2. GROOVY-2157

Elvis operator is evaluating the "true" expression twice


    • Type: Bug
    • Status: Closed
    • Priority: Major
    • Resolution: Fixed
    • Affects Version/s: 1.1-beta-3
    • Fix Version/s: 1.1-rc-1
    • Component/s: lexer, parser, syntax
    • Labels:


      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




            • Assignee:
              blackdrag Jochen Theodorou
              barspi Barzilai Spinak
            • Votes:
              0 Vote for this issue
              0 Start watching this issue


              • Created: