In the following sample, I can pass a Consumer<Optional<Integer>
to foo
, but not a Consumer<Optional<Number>>
. On the other hand, I can pass either type to foo2
, but then I can't call the accept method of the consumer from the method body. Is there a way to change the foo
method so that this works? My initial intuition was to try void foo(Consumer<Result<? super T>> c)
but that apparently doesn't mean what I would assume.
import java.util.Optional;
import java.util.function.Consumer;
public class test<T> {
public void foo(Consumer<Optional<T>> c) {
Optional<T> t = null;
c.accept(t); // compiles
}
public void foo2(Consumer<? extends Optional<? super T>> c) {
Optional<T> t = null;
c.accept(t); // doesn't compile
}
public static void bar() {
test<Integer> t = null;
Consumer<Optional<Number>> crn = null;
Consumer<Optional<Integer>> cri = null;
t.foo(cri); // compiles
t.foo(crn); // doesn't compile
t.foo2(cri); // compiles
t.foo2(crn); // compiles
}
}