Self Executing Anonymous Functions via Lambdas

一个人想着一个人 提交于 2019-11-28 00:39:16

问题


In javascript, there's the common pattern of creating an anonymous function and immediately invoking it (usually this is called a self-executing anonymous function or an immediately-invoked function expression).

With Java 8 lambdas, is there a standard way to replicate this behaviour? Something like (() -> doSomething())().

This question asks basically the same question, but for Java 7. I'm explicitly looking for constructs which utilize lambdas.


回答1:


Not without declaring the type as well. Since Java is a statically-typed language, and functions are not first class citizens, the compiler needs to know what type your lambda is. A function can't just be free-floating, it always needs to be associated with either a class or an instance of a class.

Runnable r = () -> {
    System.out.println("Hello world!");
};
r.run();

But: You can cast the lambda to the Runnable type, and give the compiler a hint as to what kind of @FunctionalInterface you're implementing:

((Runnable)() -> {
    System.out.println("Hello world!");
}).run();

Or without the braces, which makes it a one-liner:

((Runnable)() -> System.out.println("Hello world!")).run();

I imagine that's about as close as you'll get!




回答2:


What about something like

((Runnable)(() -> System.out.println("Foobar"))).run();


来源:https://stackoverflow.com/questions/38122121/self-executing-anonymous-functions-via-lambdas

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!