编译器将方法签名与功能接口匹配.
Integer foo(){...}
Integer foo(Number x){...}
Supplier<Number> f1 = this::foo; // ()->Number, matching the 1st foo
Function<Integer, Number> f2 = this::foo; // Int->Number, matching the 2nd foo
Run Code Online (Sandbox Code Playgroud)
本质上,f2是可以接受Integer并返回的东西,Number编译器可以发现第二个foo()符合要求.
lambda表达式可以在哪里使用?
方法或构造函数参数,其目标类型是相应参数的类型.如果方法或构造函数被重载,则在lambda表达式与目标类型匹配之前使用通常的重载解析机制.(在重载解析之后,可能仍有多个匹配方法或构造函数签名接受具有相同功能描述符的不同功能接口.在这种情况下,lambda表达式必须转换为这些功能接口之一的类型);
转换表达式,显式提供目标类型.例如:
Object o = () -> { System.out.println("hi"); }; // Illegal: could be Runnable or Callable (amongst others)
Object o = (Runnable) () -> { System.out.println("hi"); }; // Legal because disambiguated
Run Code Online (Sandbox Code Playgroud)
因此,如果存在模糊签名,则需要进行转换.
| 归档时间: |
|
| 查看次数: |
3003 次 |
| 最近记录: |