7

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.

4

2 回答 2

13

并非没有声明类型。由于 Java 是一种静态类型语言,并且函数不是一等公民,因此编译器需要知道您的 lambda 是什么类型。函数不能只是自由浮动的,它总是需要与类或类的实例相关联。

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

但是:您可以将 lambda 转换为类型,并提示编译器您正在实现Runnable哪种类型:@FunctionalInterface

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

或者没有大括号,这使它成为单线:

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

我想这和你能得到的差不多!

于 2016-06-30T11:49:55.353 回答
2

怎么样的东西

((Runnable)(() -> System.out.println("Foobar"))).run();
于 2016-06-30T11:50:23.543 回答