Why not use mutableLiveData of the val type as a substitute for the var type?
Isn't it a violation to be able to set on the val type?
Like, for example:
- Example of a val type
class LoadDetailViewModel : ViewModel() {
private val _liveData = MutableLiveData<String>()
val liveData: LiveData<String> get() = _liveData
fun loadData() = viewModelScope.launch {
_liveData.value = "value"
_liveData.postValue("value")
}
}
- Code changed to var type
class LoadDetailViewModel : ViewModel() {
private var _liveData = MutableLiveData<String>()
var liveData: LiveData<String> get() = _liveData
fun loadData() = viewModelScope.launch {
_liveData.value = "value"
_liveData.postValue("value")
}
}
But the result is still equivalent. There is no error when I declare mutableLiveData as var, but I don't know why I have to declare it as val.
- I understand that the val type in the Kotlin language is an immutable type, and the var type is a mutable type.
- Then isn't it right to declare it as a var type?
Android Developers I looked up the official documents of Android, but there was no answer to them.