Kotlin(十六) 高阶函数的简单应用

高阶函数非常适用于简化各种API的调用,一些API的原有用法在使用高阶函数简化之后,不管是在易用性还是可读性方面,都可能会有很大的提升。

所以我们可以通过高阶函数来使一些API变得更简单更易读。在我们APP存储数据时,通常会用到SharedPreferences 这个API,那么我们现在尝试使用高阶函数来简化它。

简化SharedPreferences

我们之前使用SharedPreferences时,基本需要三步

1.获取Editor对象

2.通过Editor对象存储数据

3.调用apply()方法提交数据,完成存储操作

对应代码如下:

Kotlin 复制代码
    @SuppressLint("CommitPrefEdits")
    fun saveSharedPreferences(saveString: String) {
        val edit = getSharedPreferences("fileName", Context.MODE_PRIVATE).edit()
        edit.putString("editName", "editValue")
        edit.apply()
    }

那我们该如何简化他呢?首先我们可以通过扩展函数的方式,给SharedPreferences扩展一个save函数,并且他还接收一个函数类型,那么save函数就是一个高阶函数了。

代码如下:

Kotlin 复制代码
fun SharedPreferences.save(block: SharedPreferences.Editor.() -> Unit) {
     val editor = edit()
     editor.block()
     editor.apply()
}

调用

Kotlin 复制代码
getSharedPreferences("name",Context.MODE_PRIVATE).save { 
    putString("key","value")
}
相关推荐
NiceCloud喜云6 小时前
Opus 4.8 的 Effort Control 怎么选:Low 到 Max 五档策略
android·java·大数据·前端·c++·python·spring
wordbaby6 小时前
React Native + RNOH:跨页面数据回传的最佳实践与避坑指南
前端·react native
丷丩6 小时前
MapLibre GL JS第22课:查看本地GeoJSON
前端·javascript·map·mapbox·maplibre gl js
AI玫瑰助手6 小时前
Python函数:默认参数的定义与注意事项
开发语言·python·信息可视化
油炸自行车6 小时前
Claude Code 错误:API Error: 400 Failed to deserialize the JSON body into the
开发语言·javascript·json·trae·claude code·api error 400
肩上风骋7 小时前
C++14特性
开发语言·c++·c++14特性
Front思7 小时前
AI前端工程师需要具备能力+
前端·人工智能·ai
JAVA社区8 小时前
Java高级全套教程(十)—— SpringCloudAlibaba超详细实战详解
java·开发语言·spring cloud·面试·职场和发展
弥树子8 小时前
踩坑记录:服务器内网调用接口,真实请求URL与官方公开URL不一致问题排查
开发语言·php
z落落8 小时前
C# ToCharArray + foreach遍历 + String与StringBuilder
开发语言·c#