简体   繁体   English

kotlin 中 lazy{} 与 getter() 初始化之间的区别

[英]Difference between lazy{} vs getter() initialization in kotlin

In kotlin we can use both of these approach lazy{} and getter()在 kotlin 中,我们可以同时使用这两种方法lazy{}getter()

lazy initializaiton:延迟初始化:

internal val connector by lazy {
        serviceConnector
    }

getter():吸气剂():

internal val connector : ServiceConnector
        get() = serviceConnector

When to use which approach and what actually does these two approach under the hood.何时使用哪种方法以及这两种方法在幕后实际做了什么。 Which one is best approach?哪一种是最好的方法?

When you use the lazy delegate, the val is initialized only when you use it the first time.使用lazy委托时,仅在第一次使用时才初始化val So, in your code, the first time you access connector , the code inside the lambda is run, and the result is assigned to the val .因此,在您的代码中,第一次访问connector ,将运行 lambda 中的代码,并将结果分配给val

get() , instead, is used to redefine what happens when you try to access the val .相反, get()用于重新定义尝试访问val时发生的情况。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM