以下代码来自项目play-billing-samples。
private val repository
是val
,为什么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
}
...
}
答案 0 :(得分:0)
出于初始化val
变量的目的,声明行,任何初始化程序块(init { ... }
块)和构造函数等价于在定义点进行初始化,因为它们都在运行之前运行该对象被认为是正确构造的。
任何val
变量必须在声明,所有初始化程序块和构造函数的组合中完全初始化一次。