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

Closure access to variables can create local variable or not

    XMLWordPrintableJSON

Details

    • Bug
    • Status: Closed
    • Major
    • Resolution: Not A Problem
    • 1.8.5
    • None
    • None
    • Windows command line

    Description

      While trying to override a variable with def in a closure, I discovered that leaving the def out creates an order dependant execution. This would likely confuse novice developers (though I understand why it happens).

      e.g. consider this code:


      def out_closed_x = {
      def x=0
      println x
      }

      def x = 99
      println x
      out_closed_x()


      This will output
      99
      0
      99
      But, if first comment is uncommented and the second comment applies to the whole line, i.e.


      def x = 99

      def out_closed_x = {
      x=0
      println x
      }

      // def x = 99 //
      println x
      out_closed_x()
      println x


      The output is
      99
      0
      0

      This is (presumably) because the local variable instantiated (by default) in the first examples continues to be referenced by the closure, but the global variable is overwritten in the second instance.

      If a def is used in the closure, then things are better - since the second version won't run.

      However, I can see this being confusing. I just wish I had a solution.

      BTW - Groovy is great and I would just like it to be even better

      Attachments

        Activity

          People

            blackdrag Jochen Theodorou
            ssstratton Andrew Stratton
            Votes:
            0 Vote for this issue
            Watchers:
            1 Start watching this issue

            Dates

              Created:
              Updated:
              Resolved: