【19】Kotlin语法进阶——Kotlin高阶函数的应用

提示:此文章仅作为本人记录日常学习使用,若有存在错误或者不严谨得地方欢迎指正。

文章目录

一、高阶函数的应用

高阶函数非常适合用来简化各种API的调用,本章我们将运用高阶函数的知识来简化SharedPreferences这个API。

1.1 SharedPreferences的简化

在前面的文章中,我们学习并使用了SharedPreferences来实现数据持久化的功能。在得到了SharePreferences对象后,如果想将数据存储到SharePreferences文件中,需要以下几个步骤:

  1. 调用SharePreferences对象的edit()方法获取一个SharePreferences.Editor对象
  2. 向SharePreferences.Editor对象中添加数据(putBoolean()、putString等)
  3. 通过apply( )方法提交所添加的数据,完成数据的存储

对应的代码示例如下:

kotlin 复制代码
//通过getSharedPreferences().edit()方法获得Editor对象
val myEditor = getSharedPreferences("shared_prefs_data", MODE_PRIVATE).edit()
//以键值对的方式向Editor对象中添加数据
myEditor.putString("name", "CodingBear")
myEditor.putInt("age", 18)
myEditor.putBoolean("single", true)
//将数据存储到SharePreferences文件中
myEditor.apply()

接下来,我们尝试使用Kotlin高阶函数来简化SharedPreferences的用法。新建一个SharedPreferences.kt文件,然后在里面加入以下代码:

kotlin 复制代码
//扩展函数open期望接收一个lambda函数作为参数,并且这个lambda函数将在扩展函数内部被调用
fun SharedPreferences.open(block:SharePreferences.Editor.()->Unit){
    val editor = edit()
    // 在lambda函数内部对editor进行操作
    editor.block()
    editor.apply()
}

可以看到,我们首先定义了一个SharedPreferences的扩展函数open() ,并让它接收一个函数类型的参数 ,因此open()就是一个高阶函数 。由于扩展函数open()拥有SharedPreferences的上下文,因此这里可以直接调用edit()方法来获取SharePreferences.Editor对象 。由于open()接收的是一个SharedPreferences.Editor的函数类型参数 ,因此这里需要调用editor.block()对函数类型参数进行调用,我们就可以在函数类型参数的具体实现中添加数据了。最后调用apply( )方法提交所添加的数据,完成数据的存储。

在定义好open()后,我们在项目中使用SharedPreferences存储数据就会更加的简单:

kotlin 复制代码
getSharedPreferences("shared_prefs_data", MODE_PRIVATE).open{
	putString("name", "CodingBear")
	putInt("age", 18)
	putBoolean("single", true)
}

可以看到,我们直接在SharedPreferences对象上调用open(),然后在Lambda表达式中完成数据的添加操作即可。Lambda表达式拥有SharePreferences.Editor的上下文,所以我们直接调用putXXX()方法添加数据即可。最后我们也不需要调用apply()方法来提交数据,因为open()函数会自动完成提交操作。
其实Google的KotlinX扩展库中已经包含了上述SharePreferences的简化用法 ,这个扩展库会在Android Studio创建项目的时候会被自动导入到build.gradle.kts(:app)的dependencies中:

因此我们可以直接在项目中使用如下写法向SharePreferences中存储数据:

kotlin 复制代码
                          注意:使用的是Kotlin自带扩展库中的edit{}不是SharePreferences类的edit()
getSharedPreferences("data", Context.MODE_PRIVATE).edit {
    putString("name", "CodingBear")
    putInt("age", 18)
    putBoolean("single", true)
}

可以看到,其实就是将open()换成了edit{},其余的写法都是一模一样的。你在正式项目中完全可以使用Kotlin扩展库自带的edit{},但是掌握高阶函数优化API这种方式对你后续的编程会有很大的帮助。

相关推荐
人工智能训练师1 小时前
Ubuntu22.04如何安装新版本的Node.js和npm
linux·运维·前端·人工智能·ubuntu·npm·node.js
Seveny071 小时前
pnpm相对于npm,yarn的优势
前端·npm·node.js
yddddddy2 小时前
css的基本知识
前端·css
昔人'2 小时前
css `lh`单位
前端·css
前端君3 小时前
实现最大异步并发执行队列
javascript
Nan_Shu_6144 小时前
Web前端面试题(2)
前端
知识分享小能手4 小时前
React学习教程,从入门到精通,React 组件核心语法知识点详解(类组件体系)(19)
前端·javascript·vue.js·学习·react.js·react·anti-design-vue
蚂蚁RichLab前端团队5 小时前
🚀🚀🚀 RichLab - 花呗前端团队招贤纳士 - 【转岗/内推/社招】
前端·javascript·人工智能
丑小鸭是白天鹅5 小时前
Kotlin协程详细笔记之切线程和挂起函数
开发语言·笔记·kotlin
程序员江同学5 小时前
ovCompose + AI 开发跨三端的 Now in Kotlin App
android·kotlin·harmonyos