🔥码云GVP开源项目 12k star Uniapp+ElementUI 功能强大 支持多语言、二开方便! 广告
# 1. 什么是高阶函数 `Lambda`表达式还可以作为函数的**实际参数或者返回值**存在,而这种声明,在`Kotlin`中叫做**高阶函数**。 # 2. 将Lambda作为参数 比如下面的案例: ~~~ /** * 排序列表 */ fun sort(list: List<Int>, function: (Int, Int) -> Boolean): List<Int> { var temp = list.toMutableList() var len = list.size for(i in 0..(len - 1)){ var index = i for(j in (i+1)..(len - 1)){ if(function(temp[index], temp[j])){ index = j } } if(index != i){ var t = temp[i] temp[i] = temp[index] temp[index] = t } } return temp } fun printList(list: List<Int>){ for (i in list) { print("${i}\t") } println() } fun main() { var a = listOf<Int>(1, 2, 3, 4, 1, 8, 0) var temp = sort(a, {c: Int, b: Int -> c > b}) printList(temp) } ~~~ 结果: ``` 0 1 1 2 3 4 8 ``` 当然如果需要逆序,只需要修改为: ``` var temp = sort(a, {c: Int, b: Int -> c < b}) ``` 上面的案例是两个参数的情况,这里有种特殊情况:函数类型满足**只接收一个参数**的要求,可以用`it`关键字代替函数的形参以及箭头。比如下面的案例: ~~~ /** * 判断一个数是否是2的n次幂 */ fun Int.judgement(condition: (Int) -> Boolean): Boolean { return condition(this) } fun main() { var a = 4 // var result = a.judgement({ x: Int -> (x.and (x - 1)) == 0 }) var result = a.judgement { (it.and (it - 1)) == 0 } println(result) } ~~~ # 3. 作为返回值 在[Kotlin从基础到实战-黑马程序员编著-微信读书 (qq.com)](https://weread.qq.com/web/reader/ab3320e0718ade85ab3fd1cka87322c014a87ff679a21ea)这本书中给了一个案例,感觉能很好的说明这个问题,这里摘要一下。模拟普通用户与`VIP`用户购物的案例: ~~~ /** * 会员打8折 */ fun getPrice(user: USER): (Double) -> Double{ if(user == USER.NORMAL){ return {it} } return {it -> it * 0.8} } fun main() { // 因为返回的是一个函数,所以还可以进行传入一个Double类型的数据,然后执行 println(getPrice(USER.NORMAL)(300.0)) println(getPrice(USER.VIP)(300.0)) } ~~~ 结果: ``` 300.0 240.0 ```