Reputation: 98
I am fairly new to Java, currently learning about lambda expressions. so I wanted to use generic with the Consumer function to make it accept any type of parameter passed to it and just print it out
The consumer accepts the first generic as the type that must be passed to it as the first param I specified it to be (? extends Object) (I thinks it means anything that extends object which means anything in java that is not primitive) so it should accept any parameter passed to it including the list I am creating, but no error happens.
Supplier<List<String>> listSupplier = () -> new ArrayList<>();
Supplier<List<String>> listSupplierTwo = ArrayList::new;
Consumer<? super Object> logger = (a) -> System.out.println(a);
Consumer<? extends Object> loggerTwo = System.out::println;
var result = listSupplier.get();
var resultTwo = listSupplierTwo.get();
logger.accept("fooooo"); // compiles
logger.accept(result); // compiles
loggerTwo.accept(resultTwo); // error
loggerTwo.accept("fooooo"); // error
when replacing the extends with super(? super Object)(I think it means anything that is super class of Object class which is nothing as super dosent extend anything) it accepts any param and everything works
I searched a lot maybe I have incorrect understanding of how extends and super works may be I am incorrectly using the wildcard ? should I only use it with only collections ?
Upvotes: 1
Views: 55