Generic type vs wildcard compile issue in java

Question

I am facing a generic vs wildcard issue in java.

class A<T> {
    T value;
}

class B<T> {
    T value;
}

public <T> A<? extends B<T>> methodA() {

    A<B<Object>> gg = fetchFromSomeLocation();
    return (A<? extends B<T>>) gg;
}

public <T, E extends B<T>> A<E> methodB() {

    A<B<Object>> gg = fetchFromSomeLocation();
    return (A<E>) gg;
}

So methodB() compiles fine, no issue. But methodA causes compilation to fail with:

incompatible types: A<B<java.lang.Object>> cannot be converted to A<? extends B<T>>

I am not able to understand why this is so.

P.S on Intellij it shows as fine valid code.

EDIT

so apparently this compiles just fine

public static <T> A<? extends B<T>> methodC() {

    A<B<Object>> gg = new A<>();
    return (A<? extends B<T>>)(A<?>) gg;
}

Show source
| generics   | java   | wildcard   | intellij-idea   2017-10-04 21:10 0 Answers

Answers to Generic type vs wildcard compile issue in java ( 0 )

Leave a reply to - Generic type vs wildcard compile issue in java

◀ Go back