Java – self executing anonymous functions via Lambdas
In JavaScript, there is a common pattern of creating an anonymous function and calling it immediately (usually called self executing anonymous function or immediately invoked function expression)
Using java 8 Lambdas, is there a standard way to replicate this behavior? Things like (() – > dosomething ()) ()
This question basically asks the same question, but for Java 7 I explicitly look for constructs that use Lambdas
Solution
Is not an undeclared type Because Java is a statically typed language and functions are not first class citizens, the compiler needs to know the type of lambda A function cannot just float, it always needs to be associated with a class or an instance of a class
Runnable r = () -> { System.out.println("Hello World!"); }; r.run();
However: you can convert lambda to runnable type and give the compiler a hint about the @ functionalinterface type you are implementing:
((Runnable)() -> { System.out.println("Hello World!"); }).run();
Or there are no parentheses, which makes it a single line:
((Runnable)() -> System.out.println("Hello World!")).run();
I think it's as close as you'll get!