lambda 表达式的隐式类型转换

Implicit type conversion for lambda expression

考虑以下 class 片段:

public void method() {
    test(() -> { });
}

void test(Runnable a) {
    System.out.println("Test 1");
}

void test(A a) {
    System.out.println("Test 2");
}

interface A extends Runnable {

}

调用方法 method() 将导致 Test 2 输出。这意味着,lambda 表达式 () -> { } 被隐式转换为 A。为什么?

这是适用于所有重载的相同标准规则。 Java will choose the most specific applicable method.

两种方法都接受函数接口类型的参数。 lambda 表达式

() -> { }

可以转换为这两种类型。 ARunnable 的子类,因此更具体。因此选择参数类型为 A 的方法。