如何在计算 属性 中获取构造函数参数

How to get the constructor argument in computed property

我将 sharedPreference 对象包装到 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>()
}

如何固定myPreferences的作用域到达构造函数?

您可以使用 valvar 在主构造函数中声明 class 属性,并可选择添加访问修饰符。它将使您的构造函数参数成为属性,并且它们将在您的 class 中可用,就像您在 private val viewModelJob... 属性.

附近声明它们一样

这是一个修改了主构造函数的示例,其中它的参数声明为 private val。现在它们在 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>()
}

此特定功能的官方示例 (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) { /*...*/ }