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()
        }
    }
}
相关推荐
Ada's3 小时前
【计算机基础系列】003:Python数据结构
开发语言·数据结构·python
2601_962885723 小时前
如何用 Python 计算 TRIX 三重指数平滑均线指标?
开发语言·python
还卿一钵无情泪4 小时前
Unsloth 微调 构建自己的大模型 没有GPU也能微调
linux·开发语言·人工智能·python·大模型·nlp·unsloth
alexhilton5 小时前
模块化Jetpack Compose架构
android·kotlin·android jetpack
倔强的石头1065 小时前
应用账号最小权限实践:读写账号、报表账号、运维账号分层
java·运维·开发语言
传人once5 小时前
页面中心圆圈放大效果如何写
开发语言·javascript·ecmascript
NeilYuen5 小时前
【C++】STL源码仿写(二):vector
开发语言·c++
蜗牛互联网6 小时前
Python消费Responses SSE事件:增量文本、超时与取消
java·开发语言·人工智能·后端·python
weixin_307779136 小时前
C++代码实现MATLAB中的crossval函数功能
开发语言·c++·算法·matlab
ttwuai7 小时前
Go后台管理系统开源项目:4个官方仓库怎么追溯和核验
开发语言·golang·开源