Java中的强制转换表达式是什么?
一投的表达提供了一种机制,以明确提供 lambda表达式的类型,如果没有可以从上下文推断方便。当方法声明因不相关的功能接口类型而过载时,解决歧义也很有用。
语法
Object o = () -> { System.out.println("nhooo"); }; //非法: Object o = (Runnable) () -> { System.out.println("nhooo"); }; // Legal
示例
interface Algebra1 { int operate(int a, int b); } interface Algebra2 { int operate(int a, int b); } public class LambdaCastingTest { public static void main(String[] args) { printResult((Algebra1)(a, b) -> a + b); // Cast Expression in Lambda printResult((Algebra2)(a, b) -> a * b); // Cast Expression in Lambda } static void printResult(Algebra1 a) { System.out.println("From Algebra1 Interface: " + a.operate(40, 20)); } static void printResult(Algebra2 a) { System.out.println("From Algebra2 Interface: " + a.operate(40, 20)); } }
输出结果
From Algebra1 Interface: 60 From Algebra2 Interface: 800