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

Cannot infer correct type argument when passing a subtype of the declared type argument

    XMLWordPrintableJSON

Details

    Description

      I have the following Groovy program.

      class Foo<T> {
          T f;
          Foo (T f) {
            this.f = f;
          }
      
      }
      
      interface Bar{}
      class Baz<T> implements Bar {}
      
      @groovy.transform.TypeChecked
      class Main  {
        public static void main(String[] args) {
          Foo<Bar> x1 = new Foo<Bar>(new Baz<Integer>()) // Compiles
          Foo<Bar> x2 = new Foo<>(new Baz<Integer>()) // Does not compile
        }
      }
      

      Actual Behavior

      The program does not compile, and I get the following error.

      org.codehaus.groovy.control.MultipleCompilationErrorsException: startup failed:
      Main.groovy: 16: [Static type checking] - Incompatible generic argument types. Cannot assign Foo <Baz> to: Foo <Bar>
       @ line 16, column 19.
             Foo<Bar> x2 = new Foo<>(new Baz<Integer>())
                           ^
      
      1 error
      
      

      Expected Behavior

      Compile successfully.

      Affected Version

      I have also tested it with the compiler from Master (commit: 666627b3be7718e3265fc42b473060bc73f42e2f).

      Comment

      If I remove the type parameter from Baz, then it only fails when compiled with the compiler from the Master.
      Specifically, the following test case compiles with 3.0.7 and 4.0.0-alpha-2 compilers but fails with the same message as the previous test case when using the compiler from the Master.

      class Foo<T> {
          T f;
          Foo (T f) {
            this.f = f;
          }
      
      }
      
      interface Bar{}
      class Baz implements Bar {}
      
      @groovy.transform.TypeChecked
      class Main  {
        public static void main(String[] args) {
          Foo<Bar> x1 = new Foo<Bar>(new Baz()) // Compiles
          Foo<Bar> x2 = new Foo<>(new Baz()) // Does not compile
        }
      }
      

      Attachments

        Activity

          People

            emilles Eric Milles
            schaliasos Stefanos Chaliasos
            Votes:
            0 Vote for this issue
            Watchers:
            2 Start watching this issue

            Dates

              Created:
              Updated:
              Resolved: