Methods for generating generic Java8 signature and lambdas styles don't work

The best way to explain this is with an example:

public class Cosmos<T> {
    public void says(Consumer<String> stringConsumer) {
        stringConsumer.accept("we can");
    }
}

I expected this to work:

new Cosmos().says(s -> System.out.println(s.length()));

But NO , it does NOT work! Java8 thinks it sis Object!

However, if I define Tanything, it works:

new Cosmos<Void>().says(s -> System.out.println(s.length()));

How is it that the signature of the methods is associated with a common type?

+4
source share
1 answer

pre-Generics , , Generics , , .

, Java 5 :

ArrayList list = new ArrayList();
String[] str = list.toArray(new String[0]);

ArrayList<Number> list = new ArrayList<Number>();
String[] str = list.toArray(new String[0]);

, , toArray List ( ).

, new Cosmos(), says, . :

new Cosmos<>().says(s -> System.out.println(s.length()));

.

+8

Source: https://habr.com/ru/post/1672998/


All Articles