Java Reference
In-Depth Information
How It Works
A great use-case for lambda expressions is that they are very well suited for taking the
place of many anonymous class implementations. Most anonymous inner classes im-
plement a functional interface, which makes them perfect candidates for replacement
via lambda expressions. In the solution, the anonymous inner class for supporting a
JavaFX button action has been redesigned to work within the context of a lambda ex-
pression. Since the an EventHandler must implement one abstract method,
handle() , it becomes a good fit for a lambda implementation.
In the solution, the EventHandler lambda expression accepts an argument,
whose type is derived from the context of the expression. In this case, since the expres-
sion is implementing an EventHandler , the derived type for the argument is Ac-
tionEvent . The body of the lambda expression contains several lines of code and re-
turns nothing to the caller, as the handle() method contains a void return type.
Although the lambda expression solution does not save more than a few lines of
code, it does help increase readability and maintainability. Although anonymous inner
classes are an acceptable solution, code that is riddled with such constructs can be cum-
bersome to work with. Replacing anonymous inner classes with lambda expressions
helps to maintain succinct code that is easy to follow.
6-7. Accessing Class Variables from a
Lambda Expression
Problem
The class you are writing contains instance variables, and you would like to make them
available for use via a lambda expression within the class.
Solution
Make use of instance variables that are contained in enclosing classes, as needed, from
within lambda expressions. In the following class, the lambda expression contained
within the VariableAccessInner.InnerClass.lambdaInMethod() meth-
Search WWH ::




Custom Search