Kotlin笔记18-高阶函数的应用


11.1 高阶函数的应用

  • 简化SharedPreferences

序号

向SharePreferences存储数据的过程

1

调用其edit()方法获取SharedPreferences.Editor对象

2

向SharePreferences.Editor对象中添加数据

3

调用apply()方法将添加的数据提交,完成数据存储操作

​描述转化成代码:​

val edior=getSharedPreferences("data",Context.MODE_PRIVATE).edit()
editor.putString("name", "Tom")
editor.putInt("age", 28)
editor.putBoolean("married", false)
editor.apply()

​使用高阶函数简化:​

  1. 新建SharePreferences文件
fun SharePreferences.open(block: SharePreferences.Editor() -> Unit) {
val editor = edit()
editor.block()
editor.apply()
}

​用法:​

getSharedPreferences("data", Context.MODE_PRIVATE).open {
putString("name","Tom")
}
  1. KTX扩展库已经包含这种简化用法,也可以使用

​Example:​

getSharedPreferences("data", Context.MODE_PRIVATE).edit{
putString("name","Tom")
}

  • 简化ContentValues

名称

作用

ContentValues

结合SQLiteDataBase的API存储和修改数据库中的数据

val values = ContentValues()
values.put("name", "Game of Thrones")
values.put("author","George Martin")
values.put("pages", 720)
values.put("price", 20.85)
db.insert("Book", null, values)

​简化1:​

fun cvOf(vararg pairs: Pair<String, Any?>): ContentValues {
val cv = ContentValues()
for (pair in pairs) {
val key = pair.first
when (val value = pair.second) {
is Int -> cv.put(key, value)
is Long -> cv.put(key, value)
is Float -> cv.put(key, value)
is Double -> cv.put(key, value)
is Boolean -> cv.put(key, value)
is String -> cv.put(key, value)
is Byte -> cv.put(key, value)
is ByteArray -> cv.put(key, value)
null -> cv.putNull(key)
}
}
return cv
}

​用法:​

val values= cvOf("name" to "Game of Thrones","author" to "George Martin","pages" to 720, "price" to 20.85)
db.insert("Book",null,values)

​代码优化:​

fun cvOf(vararg pairs: Pair<String, Any?>) = ContentValues().apply {
for (pair in pairs) {
val key = pair.first
when (val value = pair.second) {
is Int -> put(key, value)
is Long -> put(key, value)
is Float -> put(key, value)
is Double -> put(key, value)
is Boolean -> put(key, value)
is String -> put(key, value)
is Byte -> put(key, value)
is ByteArray -> put(key, value)
null -> putNull(key)
}
}
}

​KTX库中也提供了同样的功能的contentValuesOf()方法,用法如下:​

val  values = contentValuesOf("name" to "Game of Thrones","author" to "George Martin", "pages" to 720,"price" to 20.85)
db.insert("Book", null, values)

ヾ(≧▽≦!)o Kotlin新特性

  1. 在kotlin中使用"Apple" to 1这样的语法结构快速创建一个键值对,会创建一个Pair对象