Game Development Reference
In-Depth Information
Lambda Expression: A Powerful New
Java 8 Feature
One of the major new features that was recently released in Java 8 during 2014 is the
lambda expression . Using the lambda expression can make your code more compact,
and allows you to turn a method into a simple Java statement using Java 8's new
lambda -> “arrow” operator. The lambda expression provides a Java code shortcut to
structure one single method interface by instead using a lambda expression.
The Java 8 lambda expression has the same features as a Java method structure, as
it requires a list of parameters to be passed in, as well as the code “body” to be speci-
fied. The code that the lambda expression calls can be a single java statement, or a
block of code, containing multiple Java programming statements. This statement (or
statements) will be expressed utilizing the parameters passed into the lambda expres-
sion. The basic Java 8 syntax for the simple lambda expression should be written as
follows:
(the parameter list) -> (a Java expression)
You can also create a complex lambda expression by using the curly braces that
are used in Java to define an entire block of Java code statements in conjunction with
the lambda expression. This would be done by using the following format:
(the parameter list) -> { statement one; statement two;
statement three; statement n; }
It is important to note that you do not have to use lambda expressions to replace
traditional Java methods! In fact, if you want your code to be compatible with Java 7,
for instance, if you want your code to also work in Android 5.0, which uses Java 7, you
do not have to utilize lambda expressions. However, since this is specifically a Java 8
game development title, and since lambda expressions are the major new feature of
Java 8, and since NetBeans will convert your Java methods to lambda expressions for
you, as you are about to see, I have decided to utilize them in this topic.
Let's take a closer look at the work process for getting NetBeans to convert your
Java methods into lambda expressions for you. As you can see in Figure 9-5 , you cur-
rently have wavy yellow warning highlights in your code.
 
Search WWH ::




Custom Search