1.

What are the types and common ways to use lambda expressions?

Answer»

A lambda expression does not have any specific type by itself. A lambda expression RECEIVES type once it is assigned to a functional INTERFACE. That same lambda expression can be assigned to different functional interface types and can have a different type.

For eg consider expression s -> s.isEmpty() :

PREDICATE<String> stringPredicate = s -> s.isEmpty(); 
Predicate<List> listPredicate = s -> s.isEmpty();
Function<String, Boolean> func = s -> s.isEmpty();
Consumer<String> stringConsumer = s -> s.isEmpty();

Common ways to USE the expression

Assignment to a functional Interface —> Predicate<String> stringPredicate = s -> s.isEmpty();
Can be passed as a parameter that has a functional type —> stream.filter(s -> s.isEmpty())
Returning it from a function —> RETURN s -> s.isEmpty()
Casting it to a functional type —> (Predicate<String>) s -> s.isEmpty()



Discussion

No Comment Found