fork download
  1. import java.util.Optional;
  2. import java.util.function.Consumer;
  3.  
  4. class test<T> {
  5.  
  6. public void foo(Consumer<Optional<T>> c) {
  7. Optional<T> t = null;
  8. c.accept(t); // compiles
  9. }
  10.  
  11. public void foo2(Consumer<? super Optional<?>> c) {
  12. Optional<T> t = null;
  13. //c.accept(t); // doesn't compile
  14. }
  15.  
  16. public static <T, S extends T> void foo3(Consumer<Optional<T>> c, test<S> test) {
  17. Optional<S> s = null;
  18. @SuppressWarnings("unchecked") // Safe because of properties of Optional.
  19. Optional<T> t = (Optional<T>) (Optional<?>) s;
  20. c.accept(t);
  21. }
  22.  
  23. public static void main(String[] args) {
  24. test<Integer> t = new test<>();
  25. Consumer<Optional<Number>> crn = c -> {};
  26. Consumer<Optional<Integer>> cri = c -> {};
  27.  
  28. foo3(cri, t); // compiles
  29. foo3(crn, t); // compiles
  30. }
  31. }
Success #stdin #stdout 0.13s 4386816KB
stdin
Standard input is empty
stdout
Standard output is empty