int add(int a, int b)=> a + b;
int subtract(a, b)=> a - b;performOperation(int a, int b, int Function(int, int) function)=>function(a, b);// //简化写法// add(a, b) => a + b;// subtract(a, b) => a - b;// performOperation(a, b, function) => function(a, b);
funadd(a: Int, b: Int)= a + b
funsubtract(a: Int, b: Int)= a - b
funperformOperation(a: Int, b: Int, action:(Int, Int)-> Int)=action(a, b)
使用
funmain(){val res11 =performOperation(1,2,::add)val res12 =performOperation(1,2, action ={ a: Int, b: Int -> a + b })val res21 =performOperation(1,2,::subtract)val res22 =performOperation(1,2, action ={ a: Int, b: Int -> a - b })println("res11: $res11")println("res12: $res12")println("res21: $res21")println("res22: $res22")}
(3)java
定义
publicclassTest{intadd(int a,int b){return a + b;}intsubtract(int a,int b){return a - b;}intperformOperation(int a,int b,BiFunction<Integer,Integer,Integer> action){return action.apply(a, b);}}
使用
publicclassTest{intadd(int a,int b){return a + b;}intsubtract(int a,int b){return a - b;}intperformOperation(int a,int b,BiFunction<Integer,Integer,Integer> action){return action.apply(a, b);}voidmain(Test test){int res11 =performOperation(1,2, test::add);int res12 =performOperation(1,2,(a, b)-> a + b);int res21 =performOperation(1,2, test::subtract);int res22 =performOperation(1,2,(a, b)-> a - b);}}
2、带参数不带返回值的方法作为入参
(1)flutter
定义
equals(int a, int b,Function(bool) callback){if(a == b){callback(true);}else{callback(false);}}// //简化写法// equals(a, b, callback) {// if (a == b) {// callback(true);// } else {// callback(false);// }// }