kotlin中体会到一些比较好用的点 1.lambda 2.object 3.泛型
·
1.List的lambda中直接访问变量
fun testList() {
val list = listOf(11, 2, 3, 4, 5, 6, 7, 8, 9, 10)
var count = 0
//在lambda中可以直接操作变量
list.forEach {
count++
}
println("count:$count")
//遍历索引
list.indices.forEach {
println("$it")
}
}
2.使用Object来管理单例Service的注册
初始化
fun testService() {
ServiceListManager.init()
}
IService
interface IService {
fun init()
val order: Int
get() = 1
}
具体的Service
package service
object AccountService : IService {
override fun init() {
println("AccountService init")
}
override val order: Int
get() {
return 3
}
}
ServiceListManager
package service
object ServiceListManager {
private val serviceList = mutableListOf<IService>(
LoginService,
AccountService
)
fun init() {
//先排序一下
serviceList.sortBy { it.order }
//初始化
serviceList.forEach {
it.init()
}
}
}
3.泛型json和map互转
package com.example.demo
import kotlinx.serialization.json.Json
suspend fun main(args: Array<String>) {
val JsonUtilV2 = Json { ignoreUnknownKeys = true; isLenient = true }
val map = mapOf(
"a" to 1,
"b" to 2,
"c" to 3
)
//map转json
val jsonStr = JsonUtilV2.encodeToString(map)
println(jsonStr)
//转为map不需要传递TypeReference
val beanMap: Map<String, Int> = JsonUtilV2.decodeFromString(jsonStr)
println(beanMap)
}
更多推荐
所有评论(0)