بله .این قابلیت که نوعی syntax خاص است از جاوا 7 به بعد پشتیبانی میشود .
public class SimpleClosure {
public static void main(String[] args) {
// function with no arguments; return value is always 42
int answer = { => 42 }.invoke();
System.out.println(answer);
}
}
//A closure with one argument:
double log = { double x => Math.log(x) }.invoke(10);
//A closure with a statement:
// this will print "31 is odd" and return 15
int half = {
int x =>
if (x % 2 != 0) System.out.printf("%d is odd%n", x); x / 2
}.invoke(31);
//A closure with two arguments:
int sum = { int x, int y => x + y }.invoke(3, 4); // will return 7
//A closure does not have to return any value (the function may have return type void):
{ char c => System.out.println(c); }.invoke('@'); // will print @
//A closure that returns a string:
String reversed = {
String s =>
new StringBuilder(s).reverse().toString()
}.invoke("abcd"); // will return "dcba"
//A closure that returns an instance of Runnable.
{ => new Runnable() {
public void run() {
System.out.println("hi from Prague");
}
}
}.invoke().run(); // invoke() returns an instance of Runnable and we
// call run() on it immediately
//We can declare local variables in closures:
{ int n =>
int m = n + 1; System.out.println(m * m);
}.invoke(3); // will print 16