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

incorrect type inference after (instanceof || instanceof)

    XMLWordPrintableJSON

Details

    • Bug
    • Status: Closed
    • Minor
    • Resolution: Duplicate
    • 3.0.17
    • None
    • Compiler
    • None

    Description

      Under static compilation, inside an "if" condition that checks if either of two variables are an instance of a class, both variables are inferred to be that class.  If one of them is not, accessing it results in a ClassCastException.

      import groovy.transform.CompileStatic
      
      @CompileStatic
      class InstanceofTypeInference {
          static abstract class BaseClass {
             abstract String getMyString()
          }
      
          static class ClassA extends BaseClass {
             String getMyString() {
                return "Class A String"
             }
          }
      
          static class ClassB extends BaseClass {
             String getMyString() {
                return "Class B String"
             }
          }
      
          void doStuff(BaseClass foo, BaseClass bar) {
             if((foo instanceof ClassA) || (bar instanceof ClassA)) {
                println foo.myString
                println bar.myString  // cannot cast ClassB to ClassA
             }
          }
      
          static void main(args) {
             def example = new InstanceofTypeInference()
             example.doStuff(new ClassA(), new ClassB())
          }
      } 

      Running this example fails with a ClassCastException.

      Attachments

        Issue Links

          Activity

            People

              emilles Eric Milles
              jasongarrett Jason Garrett
              Votes:
              0 Vote for this issue
              Watchers:
              1 Start watching this issue

              Dates

                Created:
                Updated:
                Resolved: