[英]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. 调用方法
method()
将导致Test 2
输出。 This means, that lambda expression () -> { }
was implicitly converted to A
. 这意味着,lambda表达式
() -> { }
被隐式转换为A
Why? 为什么?
It's the same standard rule applied to all overloads. 这是适用于所有重载的相同标准规则。 Java will choose the most specific applicable method.
Java将选择最具体的适用方法。
Both methods accept an argument that is of a functional interface type. 两种方法都接受一个函数接口类型的参数。 The lambda expression
lambda表达式
() -> { }
is convertible to both those types. 可转换为这两种类型。
A
is a subclass of Runnable
and is therefore more specific. A
是Runnable
的子类,因此更具体。 The method with a parameter type of A
therefore gets chosen. 因此,选择参数类型为
A
的方法。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.