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);
使用
dart复制代码
void main() {
var res11 = performOperation(1, 2, add);
var res12 = performOperation(1, 2, (a, b) => a + b);
var res21 = performOperation(1, 2, subtract);
var res22 = performOperation(1, 2, (a, b) => a - b);
print("res11: $res11");
print("res12: $res12");
print("res21: $res21");
print("res22: $res22");
}
(2)kotlin
定义
kotlin复制代码
fun add(a: Int, b: Int) = a + b
fun subtract(a: Int, b: Int) = a - b
fun performOperation(a: Int, b: Int, action: (Int, Int) -> Int) = action(a, b)
使用
kotlin复制代码
fun main() {
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
定义
java复制代码
public class Test {
int add(int a, int b) {
return a + b;
}
int subtract(int a, int b) {
return a - b;
}
int performOperation(int a, int b, BiFunction<Integer, Integer, Integer> action) {
return action.apply(a, b);
}
}
使用
java复制代码
public class Test {
int add(int a, int b) {
return a + b;
}
int subtract(int a, int b) {
return a - b;
}
int performOperation(int a, int b, BiFunction<Integer, Integer, Integer> action) {
return action.apply(a, b);
}
void main(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
定义
dart复制代码
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);
// }
// }
fun equals(a: Int, b: Int, callback: (Boolean) -> Unit) {
if (a == b) {
callback(true)
} else {
callback(false)
}
}
使用
kotlin复制代码
fun main() {
equals(1, 2, callback = { value ->
if (value) {
println("相等")
} else {
println("不相等")
}
})
}
(3)java
定义
java复制代码
public class Test {
void equals(int a, int b, Function<Boolean, Void> callback) {
if (a == b) {
callback.apply(true);
} else {
callback.apply(false);
}
}
}
使用
java复制代码
public class Test {
void equals(int a, int b, Function<Boolean, Void> callback) {
if (a == b) {
callback.apply(true);
} else {
callback.apply(false);
}
}
void main() {
equals(1, 2, (value) -> {
if (value) {
System.out.println("相等");
} else {
System.out.println("不相等");
}
return null;
});
}
}