简体   繁体   中英

Incompatible types using generics and rxjava

Stumbled upon incompatible types error cause of which I don't understand.

error: incompatible types: Flowable cannot be converted to Flowable where T is a type-variable: T extends Packet declared in method getPackets(Class)

Why is this piece of code wrong?

public Flowable<Packet> getPackets() {
        .....
}

public <T extends Packet> Flowable<T> getPackets(Class<T> type) {

    return getPackets().filter(type::isInstance);
}

Flowable and filter() are part of rxjava , filter() looks like this:

public final Flowable<T> filter(Predicate<? super T> predicate)
return getPackets().filter(type::isInstance);

returns a filtered view of getPackets() , which is of type Flowable<Packet> .

However, T can be any subclass of Packet , not just Packet . And because Java generics are invariant (eg List<Dog> isn't a List<Animal> ), this isn't compatible.

You'd need to cast the Flowable :

return getPackets().filter(type::isInstance).map(type::cast);

通过使用ofType()而不是filter()对其进行了修复。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM