Java Reference
In-Depth Information
This code when executed will print “This is awesome!!” The lambda expression () ->
System.out.println("This is awesome!!") takes no parameters and returns void. This is exactly
the signature of the run method defined in the Runnable interface.
You may be wondering, “Why can we pass a lambda only where a functional interface is
expected?” The language designers considered alternative approaches such as adding function
types (a bit like the special notation we introduced to describe the signature of lambda
expressions—we revisit this topic in chapters 15 and 16 ) to Java. But they chose this way because
it fits naturally without increasing the complexity of the language. In addition, most Java
programmers are already familiar with the idea of an interface with a single abstract method
(for example, with event handling). Try Quiz 3.3 to test your knowledge of where lambdas can be
used.
Quiz 3.3: Where can you use lambdas?
Which of the following are valid uses of lambda expressions?
1 .
execute(() -> {});
public void execute(Runnable r){
r.run();
}
2 .
public Callable<String> fetch() {
return () -> "Tricky example ;-)";
}
3 . Predicate<Apple> p = (Apple a) -> a.getWeight();
Answer:
Only 1 and 2 are valid.
The first example is valid because the lambda () -> {} has the signature () -> void, which
matches the signature of the abstract method run defined in Runnable. Note that running this
code will do nothing because the body of the lambda is empty!
Search WWH ::




Custom Search