简体   繁体   中英

Implicit type conversion for lambda expression

Consider the following piece of 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 {

}

Invoking method method() will lead to Test 2 output. This means, that lambda expression () -> { } was implicitly converted to A . Why?

It's the same standard rule applied to all overloads. Java will choose the most specific applicable method.

Both methods accept an argument that is of a functional interface type. The lambda expression

() -> { }

is convertible to both those types. A is a subclass of Runnable and is therefore more specific. The method with a parameter type of A therefore gets chosen.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM