For example LiveData in Android
open class LiveData<T> {
protected open fun postValue(v: T) {
// post value
}
}
class MutableLiveData<T> : LiveData<T>() {
public override fun postValue(v: T) {
super.postValue(v)
}
}
class MyViewModel {
val myLiveData: LiveData<Int>
init {
myLiveData = MutableLiveData<Int>()
Thread {
myLiveData.postValue(111)
}.start()
}
}
fun main() {
val myViewModel = MyViewModel()
myViewModel.myLiveData.postValue(2222)
}
code above works fine, but a developer should define ‘myLiveData’ in one place but instantiate in another if it wants to avoid uncovering the returned type (in example MutableLiveData).
Why doesn’t kotlin allow to define a returned type for getter?
Like this:
val myLiveData = MutableLiveData<Int>()
get() : LiveData<Int>
Thanks for clarifications.