通过Lambdas自我执行匿名函数 [英] Self Executing Anonymous Functions via Lambdas
问题描述
在javascript中,有一种创建匿名函数并立即调用它的常见模式(通常这称为自动执行匿名函数或立即调用的函数表达式)。
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).
使用Java 8 lambdas,有没有一种标准的方法来复制这种行为?
类似(() - > doSomething())()
。
With Java 8 lambdas, is there a standard way to replicate this behaviour?
Something like (() -> doSomething())()
.
这个问题问题基本相同,但对于Java 7.我明确地寻找利用lambdas的结构。
This question asks basically the same question, but for Java 7. I'm explicitly looking for constructs which utilize lambdas.
推荐答案
并非没有声明类型。由于Java是一种静态类型的语言,并且函数不是一等公民,因此编译器需要知道你的lambda是什么 type 。函数不能只是自由浮动,它总是需要与类或类的实例相关联。
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();
但是:您可以将lambda转换为 Runnable
类型,并给编译器一个关于你正在实现什么类型的 @FunctionalInterface
的提示:
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();
我想这就差不多了!
这篇关于通过Lambdas自我执行匿名函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!