Search code examples
androidkotlincomputed-properties

How to get the constructor argument in computed property


I wrap the sharedPreference object into viewModel.

class MyViewModel @ViewModelInject constructor(
    application: Application,
    myPreferences: MyPreference
) : AndroidViewModel(application) {

    private val viewModelJob = Job()
    private val uiScope = CoroutineScope(Dispatchers.Main + viewModelJob)

    override fun onCleared() {
        super.onCleared()
        viewModelJob.cancel()
    }

    private val _something: String
        get() = myPreferences.getStoredSomething(getApplication()) // But myPreferences can not be used in this line.
    val something = MutableLiveData<String>()
}

How to fix the scope of myPreferences to reach the constructor?


Solution

  • You can declare class properties in the primary constructor by using val or var and optionally add an access modifier. It will make your constructor arguments became properties and they will be available in your class as if you would declare them near private val viewModelJob... property.

    Here is an example with modified primary constructor where it's arguments declared as private val. Now they are visible throughout the whole scope of this class.

    class MyViewModel @ViewModelInject constructor(
        private val application: Application,
        private val myPreferences: MyPreference
    ) : AndroidViewModel(application) {
    
        ... 
    
        private val _something: String
            get() = myPreferences.getStoredSomething(getApplication())
    
        val something = MutableLiveData<String>()
    }
    

    The official example of this particular feature (source link):

    ... for declaring properties and initializing them from the primary constructor, Kotlin has a concise syntax:

    class Person(val firstName: String, val lastName: String, var age: Int) { /*...*/ }