Java Reference
In-Depth Information
shadow variables from the enclosing class. Lambda expressions can't (they'll cause a compile
error), as shown in the following code:
1 This excellent paper describes the process in more detail:
http://dig.cs.illinois.edu/papers/lambda-Refactoring.pdf .
Finally, converting an anonymous class to a lambda expression can make the resulting code
ambiguous in the context of overloading. Indeed, the type of anonymous class is explicit at
instantiation, but the type of the lambda depends on its context. Here's an example of how this
can be problematic. Let's say you've declared a functional interface with the same signature as
Runnable, here called Task (this might occur when you need interface names that are more
meaningful in your domain model):
interface Task{
public void execute();
}
public static void doSomething(Runnable r){ r.run(); }
public static void doSomething(Task a){ r.execute(); }
You can now pass an anonymous class implementing Task without a problem:
doSomething(new Task() {
public void execute() {
System.out.println("Danger danger!!");
}
});
But converting this anonymous class to a lambda expression results in an ambiguous method
call, because both Runnable and Task are valid target types:
 
Search WWH ::




Custom Search