I have faced with interesting problem
I have the following method
@Override
public Single<IResults> getResults() {
return Single.just(new ConcreteResults());
}
IResults is an interface and ConcreteResults is the implementation.
However I am getting an error
Error:(149, 27) error: incompatible types: Single<ConcreteResults> cannot be converted to Single<IResults>
How to solve this issue ? I need to have an interface to abstract return type.
However, this dirty trick seems to work :)
Single.just(new ConcreteResults())
.map(new Function<ConcreteResults, IResults>() {
@Override
public IResults apply(@NonNull ConcreteResults results) throws Exception {
return results;
}
});
Use:
@Override public Single<? extends IResults> getResults() {
return Single.just(new ConcreteResults());
}
Please remember that hieritance with genetics is a bit different.
Although IResults is a sub type of ConcreteResults, Single of ConcreteResults is NOT a sub type of Single of IResults . You need to use a wildcard to create a relationship between then
You can search for more information about it here: https://docs.oracle.com/javase/tutorial/java/generics/subtyping.html
You need to create a variable before returning the value. The compiler will figure out, that IResult is the over-type of ConcretResult. If you return it immediately the compiler does not get it.
@Test
void name() {
Single<IResult> result = getResult();
}
private Single<IResult> getResult() {
Single<IResult> just = Single.just(new Result());
return just;
}
interface IResult {
}
class Result implements IResult {
}
For 1_7 Settings you must use:
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_7
targetCompatibility JavaVersion.VERSION_1_7
}
You have to give the compiler pointers, because in 1_7 the compiler does not inference the type from definition.
private Single<IResult> getResult() {
Single<IResult> just = Single.<IResult>just(new Result());
return just;
}
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.