Skip to content

Poly Annotation on method receiver's type argument #1611

@aosen-xiong

Description

@aosen-xiong

Poly annotations are useful for associating the receiver type argument with the return type.

For example, the toArray method below associates the elements from the collection with the return array's element type.

@PolyNull @PolySigned Object[] toArray(Collection<@PolyNull @PolySigned E> this);

Example taken from https://github.com/eisop/jdk/blob/9d40ad20e43217893af1fa818edbe45ec8d11f4e/src/java.base/share/classes/java/util/Collection.java#L353.

In #793, we try to add a subtyping check for type arguments when invoking a method.

However, invoking such a method with a receiver whose type argument has different bounds is disallowed.

public class A<T> {
    void toArray(A<@PolyNull T> this){}

    void test1(A<T> a){
        a.toArray(); // disallowed, a's type is A @NonNull T extends @Nullable Object
                     // the requried receiver is A @Nullable T extends @Nullable Object
    }

    void test2(A<?> a){
        a.toArray(); // disallowed, a's type is A @NonNull ? extends @Nullable Object
                     // the requried receiver is A @Nullable captured extends @Nullable Object
    }
}

Overall, the solution currently is to disable the method receiver subtyping check when the declared method receiver has a poly annotation on its type argument. Is this sound?

Do we have an issue that keeps track of poly-annotations on method receiver type arguments? If not, please open one - we should discuss what needs to be checked to be sound. Add a link to that issue here.

Originally posted by @wmdietl in #793

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions