I have a method, which works with a list of Callable
of Mono
of different types.
How do I call it with Callable<Mono<Integer>>
and Callable<Mono<String>>
?
I tried
void mymethod(List<Callable<Mono<?>>> monoList){
}
void yourMethod1() {
Callable<Mono<Integer>> callableInt = () -> Mono.just(1);
Callable<Mono<String>> callableStr = () -> Mono.just("Hello");
List<Callable<Mono<?>>> callableList = Arrays.asList(callableInt,callableStr);
mymethod(callableList);
}
but this does not compile with error no instance(s) of type variable(s) exist so that Callable<Mono<Integer>> conforms to Callable<Mono<?>> inference variable T has incompatible bounds: equality constraints: Callable<Mono<?>> lower bounds: Callable<Mono<Integer>>, Callable<Mono<String>>
How can I change mymethod
or yourMethod1
to get those objects in a list of Mono
in mymethod
?
The reason your attempt doesn’t compile is due to the fact that generic types in Java are not covariant. In other words, Callable<Mono<Integer>>
and Callable<Mono<String>>
are not considered subtypes of Callable<Mono<?>>
, even though Mono<Integer>
and Mono<String>
are subtypes of Mono<?>
.
So, first option to fix it:
void yourMethod1() {
Callable<Mono<?>> callableInt = () -> Mono.just(1); // change type to Callable<Mono<?>>
Callable<Mono<?>> callableStr = () -> Mono.just("Hello"); // change type to Callable<Mono<?>>
List<Callable<Mono<?>>> callableList = Arrays.asList(callableInt, callableStr);
mymethod(callableList);
}
void mymethod(List<Callable<Mono<?>>> monoList) {
}
Again, since Mono<Integer>
and Mono<String>
are subtypes of Mono<?>
, the second option is to change mymethod
argument to List<Callable<? extends Mono<?>>>
:
void yourMethod1() {
Callable<Mono<Integer>> callableInt = () -> Mono.just(1);
Callable<Mono<String>> callableStr = () -> Mono.just("Hello");
List<Callable<? extends Mono<?>>> callableList = Arrays.asList(callableInt, callableStr);
mymethod(callableList);
}
void mymethod(List<Callable<? extends Mono<?>>> monoList) { // change type of argument
// Your implementation here
}