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

Spurious "Closure shared variable has been assigned with various type" exception

    XMLWordPrintableJSON

Details

    • Bug
    • Status: Closed
    • Major
    • Resolution: Fixed
    • 2.0.0, 2.0.1
    • 2.0.2
    • Static Type Checker
    • None
    • 64-bit Linux JDK 1.7.0.5

    Description

      Compiling this fails:

      import groovy.transform.TypeChecked
      
      @TypeChecked
      class Foo {
      
          private void doIt() {
              Closure<Void> c = {
                  List<String> list = new ArrayList<String>()
                  String s = "foo"
                  10.times {
                      list.add(s)
                  }
              }
          }
      }
      
      org.codehaus.groovy.control.MultipleCompilationErrorsException: startup failed:
      Foo.groovy: 11: [Static type checking] - A closure shared variable [list] has been assigned with various types and the method [add(java.lang.Object <E>)] does not exist in the lowest upper bound of those types: [java.util.ArrayList <java.lang.String>]. In general, this is a bad practice (variable reuse) because the compiler cannot determine safely what is the type of the variable at the moment of the call in a multithreaded context.
       @ line 11, column 17.
                         list.add(s)
                         ^
      
      1 error
      

      The error only occurs when a closure is involved. The following works fine:

      import groovy.transform.TypeChecked
      
      @TypeChecked
      class Bar {
          void doIt() {
              List<String> list = new ArrayList<String>()
              String s = "foo"
              10.times {
                  list.add(s)
              }
          }
      }
      

      Attachments

        Activity

          People

            melix Cédric Champeau
            mpierce Marlon Pierce
            Votes:
            0 Vote for this issue
            Watchers:
            2 Start watching this issue

            Dates

              Created:
              Updated:
              Resolved: