当前位置:网站首页>Application of kotlin - higher order function
Application of kotlin - higher order function
2022-07-02 08:35:00 【I can still size it.】
Higher order functions are very suitable for simplifying various functions API Call to , some API The original usage of is simplified by using higher-order functions , Whether in terms of ease of use or readability , May be greatly improved .
simplify SharedPreferences Usage of
The most primitive direction I learned before SharedPreferences The code for storing data in is as follows :
// obtain SharedPreferences.Editor object
val editor = getSharedPreferences("data",Context.MODE_PRIVATE).edit()
editor.putString("name","ZLS") // add to String Type data
editor.putInt("age",18)
editor.putBoolean("married",false)
editor.apply() // Submit data
But in the extension library indicated by the red arrow , Added his simplified usage
It contains a code similar to the following , Can greatly facilitate SharedPreferences Use
fun SharedPreferences.edit(block: SharedPreferences.Editor.() -> Unit){
val editor = edit()
editor.block()
editor.apply()
}
Extend the function to SharedPreferences
Class added a edit
function , And it also receives a function type parameter , therefore edit
Function is naturally a higher-order function . because edit
Owned in function SharedPreferences
The context of , Therefore, it can be called directly here edit()
Method to get SharedPreferences.Editor
object . in addition edit
The function receives a SharedPreferences.Editor
Function type parameters for , So we need to call editor.block()
Calling a function type parameter , We can add data to the specific implementation of function type parameters . Finally, call editor.apply()
Method to submit data , So as to complete the data storage operation .
The simplified code is as follows :
getSharedPreferences("data",Context.MODE_PRIVATE).edit{
putString("name","ZLS")
putInt("age",18)
putBoolean("married",false)
}
simplify ContentValues Usage of
ContentValues
Mainly used for combination SQLiteDatabase
Of API Storing and modifying data in a database , Specific basic usage, such as Next :
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)
The following describes how to make it simple by creating a new method :
First new ⼀ individual ContentValues.kt
file , And then define a cvOf()
Method :
fun cvOf(vararg pairs: Pair<String, Any?>): ContentValues {
}
The purpose of this method is to build a ContentValues
object .
First ,cvOf()
Method receives a Pair
Parameters , That is to use A to B
Parameter type created by syntax structure , But a parameter is added in front of it vararg
keyword , It corresponds to Java Variable parameter list in , Allow passing... To this method 0 individual 、1 individual 、2 One or even any number Pair
Parameters of type , These parameters are assigned to use vararg
Above this variable declared , And then use for-in
Loop can traverse all the parameters passed in .
Let's look at the statement Pair
type . because Pair Is a data structure of key value pairs , Therefore, you need to specify the type of data corresponding to its key and value through generics .ContentValues
All keys of are string type , Here you can put Pair
The generic type of the key is specified as String
. but ContentValues
There can be many types of values ( String type 、 integer 、 floating-point , Even null
), So we need to Pair
The generic type of the value is specified as Any?
. This is because Any
yes Kotlin Common base class for all classes in , amount to Java Medium Object
, and Any?
It means that null values are allowed to be passed in .
fun cvOf(vararg pairs: Pair<String, Any?>): ContentValues {
val cv = ContentValues()
for (pair in pairs) {
val key = pair.first
val value = pair.second
when (value) {
is Int -> cv.put(key, value)
is Long -> cv.put(key, value)
is Short -> 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
}
when
Statement entry Int
After conditional branch , Under this condition value
Will be automatically converted to Int
type , Instead of Any?
type , So you don't need to be like Java In that way, another downward transformation , This function is if
The same applies in the statement .
With this cvOf()
After method , Use ContentValues
It becomes easier when , For example, you can insert a piece of data into the database and write :
val values = cvOf("name" to "Game of Thrones", "author" to "George Martin", "pages" to 720, "price" to 20.85)
db.insert("Book", null, values)
Besides , You can also use apply
Function for secondary optimization
fun cvOf(vararg pairs: Pair<String, Any?>) = ContentValues().apply {
for (pair in pairs) {
val key = pair.first
val value = pair.second
when (value) {
is Int -> put(key, value)
is Long -> put(key, value)
is Short -> 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)
}
}
}
As mentioned above KTX A library with the same function is also provided in the library contentValuesOf()
Method , Usage is as follows :
val values = contentValuesOf("name" to "Game of Thrones", "author" to "George Martin", "pages" to 720, "price" to 20.85)
db.insert("Book", null, values)
Usually when writing code , Use it directly KTX Provided contentValuesOf()
The method is ok .
边栏推荐
- Introduction to parameters of CarSim pavement 3D shape file
- The best blog to explain the basics of compilation (share)
- 群辉 NAS 配置 iSCSI 存储
- STM32 new project (refer to punctual atom)
- Web安全--核心防御机制
- C language custom type enumeration, Union (clever use of enumeration, calculation of union size)
- idea中注释代码取消代码的快捷键
- 类和对象(类和类的实例化,this,static关键字,封装)
- Matlab-其它
- Matlab-其它
猜你喜欢
Carla-UE4Editor导入RoadRunner地图文件(保姆级教程)
ICMP Protocol
ARP and ARP Spoofing
Routing foundation - dynamic routing
OpenShift构建镜像
sqli-labs第1关
Carsim problem failed to start Solver: Path Id Obj (X) was set to y; Aucune valeur de correction de xxxxx?
STM32-新建工程(参考正点原子)
Linked list classic interview questions (reverse the linked list, middle node, penultimate node, merge and split the linked list, and delete duplicate nodes)
Web security -- Logical ultra vires
随机推荐
W10 is upgraded to W11 system, but the screen is black, but the mouse and desktop shortcuts can be used. How to solve it
Use of opencv3 6.2 low pass filter
Summary of one question per day: String article (continuously updated)
IP协议与IP地址
STM32-新建工程(参考正点原子)
Use the numbers 5, 5, 5, 1 to perform four operations. Each number should be used only once, and the operation result value is required to be 24
Solid principle: explanation and examples
Summary of one question per day: linked list (continuously updated)
Gateway is easy to use
ARP and ARP Spoofing
sqli-labs(POST类型注入)
Data asset management function
c语言自定义类型——结构体,位段(匿名结构体,结构体的自引用,结构体的内存对齐)
Summary of one question per day: stack and queue (continuously updated)
Linked list classic interview questions (reverse the linked list, middle node, penultimate node, merge and split the linked list, and delete duplicate nodes)
Network security - summary and thinking of easy-to-use fuzzy tester
Animation synchronization of CarSim real-time simulation
Deep understanding of JVM
Opencv's experience of confusing X and Y coordinates
C language custom types - structure, bit segment (anonymous structure, self reference of structure, memory alignment of structure)