[英]Sealed class in Kotlin, Incompatible types error cannot return parent type
I have this sealed class represent the view state我有这个密封的 class 代表视图 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这里我使用 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)这条线太疯狂了 emitSource(cache) 给我 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>>
.您将cache
定义为LiveData<ViewState.Success<T>>
,它与LiveData<ViewState<T>>
<ViewState<T>> 的返回类型不匹配。
You have to change the type from val cache: LiveData<ViewState.Success<T>>
to val cache: LiveData<ViewState<T>>
.您必须将类型从val cache: LiveData<ViewState.Success<T>>
更改为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)
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.