kotlin中体会到一些比较好用的点

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()
        }
    }
}
相关推荐
alexhilton5 小时前
MVI模式的完整历史、误解和现代Android范式
android·kotlin·android jetpack
benchmark_cc7 小时前
如何用 Python + QuantDash 快速构建高胜率“配对交易(Pairs Trading)”策略?
开发语言·人工智能·python·pandas·量化交易·quantdash
程序员无隅8 小时前
Coding Agent 为什么压缩上下文后还能继续工作?上下文模块设计拆解
java·开发语言·数据库
Python+998 小时前
Java 枚举类(Enum)详解:从基础到高级应用
java·开发语言·python
二炮手亮子9 小时前
浅记java线程池
java·开发语言
zmzb01039 小时前
C++课后习题训练记录Day157
开发语言·c++
dunge20269 小时前
2026年7月最新ChatGPT Plus / Pro 与 Codex:当 AI Agent 最新5.6版本来袭,必须理解事务、幂等与补偿
开发语言·人工智能·python
心中有国也有家11 小时前
AtomGit Flutter 鸿蒙客户端:Canvas 绘制进阶-路径、渐变与混合模式
android·javascript·flutter·华为·harmonyos
爱吃牛肉的大老虎11 小时前
rust基础之环境搭建
java·开发语言·rust
openKylin11 小时前
与全球技术演进同频,openKylin 3.0从C迈向Rust
c语言·开发语言·rust·开源·开放原子·openkylin