![](/img/trans.png)
[英]Error:(124, 62) error: incompatible types: Class cannot be converted to Context
[英]Sealed class in Kotlin, Incompatible types error cannot return parent type
我有這個密封的 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>()
}
這里我使用 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)
}
這條線太瘋狂了 emitSource(cache) 給我 emitSource(cache)
Required:
LiveData<ViewState<T>>
Found:
LiveData<ViewState.Success<T>>
這是一個簡單的類型定義問題。 您將cache
定義為LiveData<ViewState.Success<T>>
,它與LiveData<ViewState<T>>
<ViewState<T>> 的返回類型不匹配。
您必須將類型從val cache: LiveData<ViewState.Success<T>>
更改為val cache: LiveData<ViewState<T>>
。
這是正確的功能:
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.