简体   繁体   中英

Sealed class in Kotlin, Incompatible types error cannot return parent type

I have this sealed class represent the view state

sealed class ViewState<out ResultType>(
) {
    data class Success<ResultType>(val data: ResultType?) : ViewState<ResultType>()
    data class Error(val message: String) : ViewState<Nothing>()
    object Loading : ViewState<Nothing>()

}

here I use viewState

fun <T, A> performGetOperation(databaseQuery: () -> LiveData<T>)): LiveData<ViewState<T>> =
        liveData(Dispatchers.IO) {
        emit(ViewState.Loading)
        val cache: LiveData<ViewState.Success<T>> = databaseQuery.invoke()
                    .map { ViewState.Success<T>(it) }

        emitSource(cache)
        }

this line is crazy emitSource(cache) give me emitSource(cache)

Required:
LiveData<ViewState<T>>
Found:
LiveData<ViewState.Success<T>>

It was a simple type definition problem. You defined cache as LiveData<ViewState.Success<T>> which does not match the returning type of LiveData<ViewState<T>> .

You have to change the type from val cache: LiveData<ViewState.Success<T>> to val cache: LiveData<ViewState<T>> .

Here is the correct functions:

fun <T, A> performGetOperation(databaseQuery: () -> LiveData<T>)): LiveData<ViewState<T>> = liveData(Dispatchers.IO) {
  emit(ViewState.Loading)
  
  val cache: LiveData<ViewState<T>> = databaseQuery.invoke()
                    .map { ViewState.Success<T>(it) }

  emitSource(cache)
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM