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

Closures do not localize variables.

    XMLWordPrintableJSON

Details

    • Bug
    • Status: Closed
    • Major
    • Resolution: Fixed
    • 1.0-beta-9
    • 1.0-JSR-2
    • None
    • None
    • Win XP, JDK 5.0_01

    Description

      images.each { img |
      print "Downloading image #${index}...";
      imgResp = wc.getResponse(img.request);
      println "Ok";

      filename = "images/report${index}.png";
      print "Saving image to ${filename}...";
      new File(filename).withOutputStream { os |
      imgResp.inputStream.eachByte

      { b | os.write(b.toInteger()) }

      ;
      }
      println "Ok";

      ...

      index++;
      }

      // save html
      filename = "bug-report.html";

      ==================
      The var in question is filename (in closure and at the very end). If the code is run as is, it fails after 'Downloading image...' message (image is downloaded) with a NullPointerException. Very misleading. If the last line is removed everything is fine.

      I saw a 'feature' of closures providing a kind of pointers to local variables. While this may be useful at times, if your target is be Java-like, this case feels very very unnatural. Besides, the failure message and the place it fails at make you scratch your head without no idea.

      Attachments

        Activity

          People

            blackdrag Jochen Theodorou
            aperepel Andrew Grande
            Votes:
            0 Vote for this issue
            Watchers:
            1 Start watching this issue

            Dates

              Created:
              Updated:
              Resolved: