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

Invalid code generated after instanceof test

    XMLWordPrintableJSON

Details

    • Bug
    • Status: Closed
    • Major
    • Resolution: Duplicate
    • 3.0.13
    • None
    • None
    • None

    Description

      Code similar to (all classes have @CompileStatic annotation):

      01| class Base { String getName() { ... } }
      02| class SubclassA extends Base {}
      03| class SubclassB extends Base {}
      04| 
      05| def instance = produceSubclassInstance()
      06| instance?.with {
      07|     if ((some other condition) || (instance instanceof SubclassA)) {
      08|         someMethod(instance.name)
      09|     }
      10| }

      throws ClassCastException:

      org.codehaus.groovy.runtime.typehandling.GroovyCastException: Cannot cast object 'SubclassB@...[...]' with class 'SubclassB' to class 'SubclassA' 

      in line 8 when method produceSubclassInstance() returns instance of SubclassB.

      Such a construction works fine on Groovy 3.0.12.

      Moreover after changing lines 6-10 to:

      06| if (instance != null) {
      07|     if ((some other condition) || (instance instanceof SubclassA)) {
      08|         someMethod(instance.name)
      09|     }
      10| } 

      it works fine on Groovy 3.0.13 too.

      It seems like the condition (instance instanceof SubclassA) forces compiler to assume concrete subtype inside the if block when the if block is inside closure.

      Attachments

        Issue Links

          Activity

            People

              Unassigned Unassigned
              szczepan.kuzniarz Szczepan Kuzniarz
              Votes:
              0 Vote for this issue
              Watchers:
              2 Start watching this issue

              Dates

                Created:
                Updated:
                Resolved: