1,自定义高阶函数接收一个函数类型的参数
定义高阶函数,
传入两个参数,
传入一个函数,
函数结果抽象,来实现他们不同的逻辑
private fun resultNumber(num1: Int, num2: Int, result: (Int, Int) -> Int): Int {
return result(num1, num2)
}
调用函数
fun main() {
val result1 = resultNumber(1, 2) { num1, num2 ->
num1 + num2
}
println("result1 = $result1")
val result2 = resultNumber(1, 2) { num1, num2 ->
num1 * num2
}
println("result2 = $result2")
val result3 = resultNumber(1, 2) { num1, num2 ->
num1 % num2
}
println("result3 = $result3")
}
result1 = 3
result2 = 2
result3 = 1
2,自定义高阶函数将函数类型作为返回值
//定义一个类
class UserEntity(var userId: Long, var userName: String, var age: Int = 0) {
constructor() : this(0, "", 0)
override fun toString(): String {
return "userName:$userName,userId:$userId,age:$age"
}
}
定义函数
//此方法用户判读用户是否为成年人.
fun isAdult(): (UserEntity) -> Boolean {
return { entity -> entity.age >= 18 }
}
使用
fun main() {
val user1 = UserEntity(100, "华晨宇", 30)
val user2 = UserEntity(101, "张碧晨", 31)
val user3 = UserEntity(103, "哇哈哈", 10)
val isAdultUser = isAdult()
println("${user1.userName}是 ${if (isAdultUser(user1)) "成年" else "儿童"}")
println("${user2.userName}是 ${if (isAdultUser(user2)) "成年" else "儿童"}")
println("${user3.userName}是 ${if (isAdult()(user3)) "成年" else "儿童"}")
}
华晨宇是 成年
张碧晨是 成年
哇哈哈是 儿童
网友评论