You are viewing a plain text version of this content. The canonical link for it is here.
Posted to notifications@groovy.apache.org by "Jason Garrett (Jira)" <ji...@apache.org> on 2023/04/10 21:14:00 UTC

[jira] [Created] (GROOVY-11008) incorrect type inference after (instanceof || instanceof)

Jason Garrett created GROOVY-11008:
--------------------------------------

             Summary: incorrect type inference after (instanceof || instanceof)
                 Key: GROOVY-11008
                 URL: https://issues.apache.org/jira/browse/GROOVY-11008
             Project: Groovy
          Issue Type: Bug
          Components: Compiler
    Affects Versions: 3.0.17
            Reporter: Jason Garrett


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.
{code:java}
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())
    }
} {code}
Running this example fails with a ClassCastException.



--
This message was sent by Atlassian Jira
(v8.20.10#820010)