Java Reference
In-Depth Information
Within the functional programming paradigm, one of the most popular techniques is lambdas, which
are more informally called closures. 3 A lambda is a set of instructions that can be saved as a variable, passed
about through the program, and executed at a later time (possibly multiple times). To understand what this
means, consider a simple for loop, such as in Listing 1-8: when the program execution encounters this loop,
it executes the loop immediately and then moves on. Imagine, instead, that you could store the loop into a
variable, and then pass it around, executing it later at some faraway location, such as in the made-up code in
Listing 1-9. That is what lambdas allow you to do; Java 8's version of this code is in Listing 1-10.
Listing 1-8. Simple Loop
for(Object it : list) {
Listing 1-9. Storing a Simple Loop (Not Real Code)
// This is not Java code
Loop printObjects = for(Object it : list) {
Listing 1-10. Storing a Simple Loop in Java 8
Consumer<Iterable> printObjects = list -> {
for(Object it : list) {
// For the record, this is the same result in more idiomatic Java 8 code:
Consumer<Iterable> printObjects = list -> list.forEach(System.out::println);
This may seem like a relatively minor language feature, but the impact of introducing lambdas was
so significant that the lambdas were too big to be a part of Java 7's Project Coin, 4 and instead became the
driving feature of Java 8. This language feature is so significant because it enables a new way of interacting
with the objects that make up a Java program: now, we can have behaviors without needing to reference an
object; and we can define verbs without first having to define a noun.
The rest of this topic will explore the implications of this new language feature, and how we can change
the way that we write Java code to take advantage of this change. The result will be more functional code in
both respects: both more function-oriented code, and also code that works better. The reason is because
we can now express more directly and succinctly our intent in certain very common cases, and we have a
powerful new tool for decomposing our code into more maintainable pieces. To understand how this works,
let's turn to a very specific and likely familiar situation in Java.
3 We will get into the language of “closure” vs. “lambda” later on. In general, a developer can get along just fine treating
them as synonyms. Java prefers “lambda,” whereas most other languages on the Java Virtual Machine prefer “closure.”
Ruby, notably, has seven variations on “lambda” and “closure,” leading to this quite entertaining exploration of the
programming language: .
4 Project Coin was a project for small change. (Get it?) Introducing lambdas was initially proposed as a bit of syntactic
sugar, but it quickly became clear that the implications of having lambdas would have wide-reaching ramifications for
the Java SDK's API.
Search WWH ::

Custom Search