Search code examples
javaandroidkotlingenericsandroid-viewmodel

Why can't I write this particular assignment in Kotlin?


I'm using the MVI pattern in a project so I wrote both State and Event classes. For the Event part inside the viewModel I'm using a private property _event of type MutableLiveData, and exposing it to the Activity as a LiveData, this way:

private val _event = MutableLiveData<Event>()
val event: LiveData<Event>
    get() {
        return _event
    }

Everything worked well until I needed to use the SingleLiveEvent class (instead of its supertype MutableLiveData) found in this sample code from Google; the SingleLiveEvent class extends MutableLiveData which in turn extends LiveData.

So I thought that I could write something like this:

private val _event: LiveData<Event> = SingleLiveEvent()
val event: LiveData<Event>
    get() {
        return _event
    }

But i get this error in the editor:

Type mismatch. Required: LiveData<ConfirmTransactionViewModel.Event> Found: SingleLiveEvent<ConfirmTransactionViewModel.Event>

What am I missing? SingleLiveEvent is a subtype of LiveData and it has the same type parameter, so why won't this assignment work?

Thanks in advance


Solution

  • Not 100% sure, but I would bet you auto-converted the SingleLiveEvent<T> Java code to Kotlin, and it declared it as a subclass of MutableLiveData<T?> instead of MutableLiveData<T>.