Add possibility to set a returned type for getter

#1

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.

1 Like
#2

There is a KEEP about that here

#3

Thanks.

#4

And it is a recurring question in this forum. Search for them to find alternative ways of solving the problem until the keep is realized.