为什么在Kotlin中为val变量分配数据?

时间:2020-08-04 03:24:29

标签: android kotlin

以下代码来自项目play-billing-samples

private val repositoryval,为什么repository = BillingRepository.getInstance(application)可以正常工作?

在我看来,必须在定义时初始化val,例如private val repository: BillingRepository by lazy {BillingRepository.getInstance(application)}

代码

class BillingViewModel(application: Application) : AndroidViewModel(application) {

    val gasTankLiveData: LiveData<GasTank>
    val premiumCarLiveData: LiveData<PremiumCar>
    val goldStatusLiveData: LiveData<GoldStatus>
    val subsSkuDetailsListLiveData: LiveData<List<AugmentedSkuDetails>>
    val inappSkuDetailsListLiveData: LiveData<List<AugmentedSkuDetails>>

    private val LOG_TAG = "BillingViewModel"
    private val viewModelScope = CoroutineScope(Job() + Dispatchers.Main)
    private val repository: BillingRepository

    init {
        repository = BillingRepository.getInstance(application)
        repository.startDataSourceConnections()
        gasTankLiveData = repository.gasTankLiveData
        premiumCarLiveData = repository.premiumCarLiveData
        goldStatusLiveData = repository.goldStatusLiveData
        subsSkuDetailsListLiveData = repository.subsSkuDetailsListLiveData
        inappSkuDetailsListLiveData = repository.inappSkuDetailsListLiveData
    }

...
}

1 个答案:

答案 0 :(得分:0)

出于初始化val变量的目的,声明行,任何初始化程序块(init { ... }块)和构造函数等价于在定义点进行初始化,因为它们都在运行之前运行该对象被认为是正确构造的。

任何val变量必须在声明,所有初始化程序块和构造函数的组合中完全初始化一次。