如果一个函数接收另一个函数作为参数,或者返回值的类型是另一个函数,那么该函数就称为高阶函数
对两个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的扩展函数的源码