在学习 Android 中的 ViewModel 时,出现了一个感觉 Kotlin 旨在解决的问题。在下面的代码中,我们可以看到 MutableLiveData 值被用于编辑值和指标。但是,我们不希望这些可变值暴露给其他任何东西,特别是 Android 生命周期的成员。我们确实希望 Android 生命周期成员有权访问读取值但不能设置它们。因此,下面显示的 3 个公开函数属于 LiveData<> 不可变类型。
是否有更简单或更简洁的方法来公开可在内部编辑的只读值?这似乎是 Kotlin 旨在避免的:样板式冗长。
class HomeListViewModel: ViewModel(){
//Private mutable data
private val repositories = MutableLiveData<List<Repo>>()
private val repoLoadError = MutableLiveData<Boolean>()
private val loading = MutableLiveData<Boolean>()
//Exposed uneditable LIveData
fun getRepositories():LiveData<List<Repo>> = repositories
fun getLoadError(): LiveData<Boolean> = repoLoadError
fun getLoadingStatuses(): LiveData<Boolean> = loading
init{...//Do some stuff to MutableLiveData<>
}
}
可能类似的非 Android 场景是:
class ImmutableAccessExample{
private val theThingToBeEditedInternally = mutableListOf<String>()
fun theThingToBeAccessedPublicly(): List<String> = theThingToBeEditedInternally
init {
theThingToBeEditedInternally.add(0, "something")
}
}
最佳答案
我不知道是否可以避免冗长。但是,我以前见过它,它通常被声明为一个属性。
private val _repositories = MutableLiveData<List<Repo>>()
val repositories : LiveData<List<Repo>>
get() = _repositories
这是惯例,请参阅 the doc here在支持属性的名称
If a class has two properties which are conceptually the same but one is part of a public API and another is an implementation detail, use an underscore as the prefix for the name of the private property:
关于android - Kotlin:不可变类型对可变类型的内部变量的只读访问,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48405101/