Java Reference
In-Depth Information
Greeter greeter = new Greeter() {
@Override
public String createGreeting(String whom) {
// Close (ie: capture) the variable here
return greeting + whom + "!";
}
};
greetWorld(greeter);
}
public static void greetWorld(Greeter greeter) {
// Have the greeter use the closed variable here
// Note that the "greeting" variable is out of scope
System.out.println(greeter.createGreeting("World"));
}
Listing 2-7. Lava 8's Lambda as a Closure
public static void main(String[] args) {
String greeting = "Hello, ";
Function<String, String> greeter = whom -> greeting + whom + "!";
greetWorld(greeter);
}
public static void greetWorld(Function<String, String> greeter) {
System.out.println(greeter.apply("World"));
}
No-Argument and Multi-Argument Lambdas
The basic lambda is one that takes a single argument, but Java does not limit you to that case: you can have
zero-argument lambdas, and you can have many-argument lambdas. 3 The syntax for each of these cases is
slightly different and more complicated than the simple case.
The syntax for a lambda with zero arguments is strange: how do you represent the absence of any
arguments? Simply using the right arrow without any arguments would lead to many ambiguous cases in
the Java syntax, so that is not an option. Instead, they introduced a placeholder for zero-argument functions,
just like numbers have a placeholder symbol for zero. That placeholder is a left parenthesis immediately
followed by a right parenthesis, which even looks like zero: () . An example of using it is in Listing 2-8; in that
listing, we create a lambda that takes no arguments and always returns 1 as a Number .
Listing 2-8. Constant Supplier of Number Instances
Supplier<Number> function = () -> 1;
3 The upper limit of arguments to a lambda function is de facto unlimited. If you discover that upper bound in the course
of normal development, you are doing something really wrong.
 
Search WWH ::




Custom Search