kotlin by lazy 的使用

by lazy 的作用

by 是在kotlin中代表者委托, lazy 懒加载

by lazy 就是委托延时处理

下面写一个demo说明下

新建一个类

复制代码
class ExportController {

    fun getName(): String? {
        return "name";
    }

    fun getAge(): Int {
        return 18;
    }

}

在mian中如下

复制代码
class MainActivity : ComponentActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.main_layout)

        val exportController by lazy { ExportController() }
        exportController.getName();
        exportController.getAge();

    }

}

在这种demo中 通过 by lazy 懒加载的ExportController,当exportController第一次被访问时,会调用ExportController。

总结:只有在首次访问exportController属性时,才会调用ExportController来创建这个实例。之后的访问都将直接返回已经创建好的ExportController实例,避免了不必要的重复初始化。

相关推荐
rocpp2 小时前
Android 多语言切换实战:从 Context 到 Android 13 应用语言适配
android·kotlin
释然小师弟3 小时前
Android开发十年:反思与回顾
android·后端·嵌入式
黄林晴5 小时前
用了这么久 Koin Scope,原来一直都用错了?
android·kotlin
爱勇宝18 小时前
我做了一个只用来搜歌词的小 App
android·前端·后端
众少成多积小致巨21 小时前
JNI (Java Native Interface) 技术手册中文参考指南
android·java·c++
唐青枫1 天前
Kotlin Context Parameters 详解:别再把 Logger、事务和配置层层往下传
kotlin
Coffeeee1 天前
如何使用Glide和Coil加载WebP动图
android·kotlin·glide
Kapaseker1 天前
5 分钟搞懂 Kotlin DSL
android·kotlin
恋猫de小郭1 天前
AI Agent 开发究竟是啥?如何用 AI 开发 Agent ?深入浅出给你一套概念
android·前端·ai编程
黄林晴1 天前
Android 17 正式发布!target 37 一大批旧代码直接不能用了
android