Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
368 views
in Technique[技术] by (71.8m points)

android - 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>>
question from:https://stackoverflow.com/questions/65868644/sealed-class-in-kotlin-incompatible-types-error-cannot-return-parent-type

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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)
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...