0

The following code is from the project play-billing-samples.

private val repository is val, why can repository = BillingRepository.getInstance(application) work well?

In my mind, a val must be initialize at definition , such as private val repository: BillingRepository by lazy {BillingRepository.getInstance(application)} .

Code

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
    }

...
}
HelloCW
  • 843
  • 22
  • 125
  • 310
  • https://stackoverflow.com/a/44361695/7666442 – AskNilesh Aug 04 '20 at 03:30
  • 1
    val must be initialized once and never be changed. It is causing no issue because you are initializing it inside init {}, as soon as BillingViewModel is initialized repository is initialized as well. If you move repository initialization out of init{} it will give an error. – Rinat Diushenov Aug 04 '20 at 03:32
  • 1
    val should be initialized only once. Either directly or inside constructor . Its a similar concept as `blank final variable in java`. – ADM Aug 04 '20 at 04:20

1 Answers1

0

For purposes of initializing val variables, the declaration line, any initializer blocks (the init { ... } blocks), and the constructor are equivalent to initializing at the point of definition, because they are all run before the object is considered properly constructed.

Any val variables must be initialized exactly once in the combination of the declaration, all initializer blocks, and the constructor.

Ryan M
  • 18,333
  • 31
  • 67
  • 74