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

Type checking error on generic property with covariant type in subclass

    XMLWordPrintableJSON

Details

    Description

      A property declared with a generic type in a superclass is not seen with the correct covariant type in a subclass narrowing the type:

      abstract class AbstractNumberWrapper<S extends Number> {
          protected final S number;
      
          AbstractNumberWrapper(S number) {
              this.number = number
          }
      }
      class LongWrapper<S extends Long> extends AbstractNumberWrapper<S> {
          LongWrapper(S longNumber) {
              super(longNumber)
          }
      
          S getValue() {
              return number;
          }
      }
      assert new LongWrapper<Long>(42L).value == 42L
      

      raises the following error when type checked:

      [Static type checking] - Cannot return value of type java.lang.Number on method returning type S
       @ line 15, column 28.
                             return number;
                                    ^
      
      1 error

      Attachments

        Activity

          People

            daniel_sun Daniel Sun
            fpavageau Frank Pavageau
            Votes:
            0 Vote for this issue
            Watchers:
            5 Start watching this issue

            Dates

              Created:
              Updated:
              Resolved: