Kotlin 高阶函数

如果一个函数接收另一个函数作为参数,或者返回值的类型是另一个函数,那么该函数就称为高阶函数

对两个int数进行运算的高阶函数

/**
* 函数类型
* (Int,Int) -> Int
* 左边是函数接收的参数,多个参数用逗号隔开,如果没有参数就()
* 右边是返回类型,如果没有返回值就用Unit,大致相当于Java中的void
*/

/**
* 加法函数
*/
fun plus(num1: Int, num2: Int): Int {
   return num1 + num2
}

/**
* 减法函数
*/
fun minus(num1: Int, num2: Int): Int {
   return num1 - num2
}

/**
* 高阶函数
*/
fun operater(num1: Int, num2: Int, operation: (Int, Int) -> Int): Int {
   return operation(num1, num2)
}

/**
* 高阶函数测试
*/
fun test() {
   //函数引用方式  对象引用::方法名称   如果是当前对象那么可以是this::方法名称,this可以省略
   println(operater(1, 2, ::plus))
   println(operater(1, 2, ::minus))
   //当函数是最后一个参数时,可以使用lambda实现multiply方法,第二行为返回值
   println(operater(3, 8) { n1, n2 ->
       n1 * n2
   })
}

执行结果

3
-1
24

KTX 中SharedPreferences的高阶函数

//基本实现,或者封装个工具类
val sp = getPreferences(MODE_PRIVATE)
val editor = sp.edit()
editor.apply {
    putString("name", "张三")
    putInt("age", 18)
    apply()
}

//使用ktx后
getPreferences(MODE_PRIVATE).edit {
    putString("name", "张三")
    putInt("age", 18)
}

KTX中SharedPreferences.edit的高阶函数,也是对sp的扩展函数

@SuppressLint("ApplySharedPref")
inline fun SharedPreferences.edit(
    commit: Boolean = false,
    action: SharedPreferences.Editor.() -> Unit
) {
    val editor = edit()
    action(editor)
    if (commit) {
        editor.commit()
    } else {
        editor.apply()
    }
}
/**
* 对edit高阶函数个人理解
*
* 两个参数
*  commit: Boolean = false,//是否及时commit提交到磁盘文件,性能考虑用apply,因为一般情况是单例操作不存在并发;如果多线程操作或者需要返回状态就使用commit;这里给了一个默认值,所以调用时候可以传也可以不传
*  action SharedPreferences.Editor.() -> Unit //证明这是SharedPreferences.Editor中的一个方法,需要使用editor对象调用
* @SuppressLint("ApplySharedPref")
* inline fun SharedPreferences.edit(//edit闭包中默认持有sp的引用
*      commit: Boolean = false,
*      action: SharedPreferences.Editor.() -> Unit
* ) {
*      val editor = edit()
*      action(editor)  //这里也可以写成editor.action()
*      if (commit) {
*          editor.commit()
*      } else {
*          editor.apply()
*      }
* }
*/

仅此记录,如有问题还请提出,谢谢

感谢:Kotlin高阶函数的应用
看了这篇文章跑去翻了SP的KTX的扩展函数的源码

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值