gpt4 book ai didi

kotlin - 为什么作者将localCacheBillingClient设计为lateinit?

转载 作者:行者123 更新时间:2023-12-02 11:52:15 25 4
gpt4 key购买 nike

代码 A 来自项目play-billing-samples ,可以看到it .

不知道为什么作者设计了localCacheBillingClientlateinit ,导致代码有点复杂,if (::localCacheBillingClient.isInitialized == false) {...}被多次调用。

我想代码 B 可以很好用吧?

代码 A

class BillingRepository private constructor(private val application: Application) :
PurchasesUpdatedListener, BillingClientStateListener {

lateinit private var localCacheBillingClient: LocalBillingDb


val subsSkuDetailsListLiveData: LiveData<List<AugmentedSkuDetails>> by lazy {
if (::localCacheBillingClient.isInitialized == false) {
localCacheBillingClient = LocalBillingDb.getInstance(application)
}
localCacheBillingClient.skuDetailsDao().getSubscriptionSkuDetails()
}

val inappSkuDetailsListLiveData: LiveData<List<AugmentedSkuDetails>> by lazy {
if (::localCacheBillingClient.isInitialized == false) {
localCacheBillingClient = LocalBillingDb.getInstance(application)
}
localCacheBillingClient.skuDetailsDao().getInappSkuDetails()
}

fun startDataSourceConnections() {
Log.d(LOG_TAG, "startDataSourceConnections")
instantiateAndConnectToPlayBillingService()
localCacheBillingClient = LocalBillingDb.getInstance(application)
}
...
}

代码 B
class BillingRepository private constructor(private val application: Application) :
PurchasesUpdatedListener, BillingClientStateListener {

private val localCacheBillingClient: LocalBillingDb by lazy {
LocalBillingDb.getInstance(application)
}

val subsSkuDetailsListLiveData: LiveData<List<AugmentedSkuDetails>> by lazy {
localCacheBillingClient.skuDetailsDao().getSubscriptionSkuDetails()
}


val inappSkuDetailsListLiveData: LiveData<List<AugmentedSkuDetails>> by lazy {
localCacheBillingClient.skuDetailsDao().getInappSkuDetails()
}

fun startDataSourceConnections() {
Log.d(LOG_TAG, "startDataSourceConnections")
instantiateAndConnectToPlayBillingService()
}
...
}

最佳答案

Kotlin - Property initialization using "by lazy" vs. "lateinit"

我相信答案就在这个线程中,并且正好低于这一点。

lateinit var 可以从任何可以看到对象的地方初始化,例如从框架代码内部,单个类的不同对象可能有多个初始化场景。 by lazy { ... } 依次定义了该属性的唯一初始值设定项,它只能通过覆盖子类中的属性来更改。如果您希望您的属性以一种可能事先未知的方式从外部初始化,请使用 lateinit。

关于kotlin - 为什么作者将localCacheBillingClient设计为lateinit?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61830836/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com