简体   繁体   English

Kotlin 中的密封 class,不兼容类型错误无法返回父类型

[英]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.

相关问题 错误:(124,62)错误:不兼容的类型:类无法转换为上下文 - Error:(124, 62) error: incompatible types: Class cannot be converted to Context 不兼容的类型错误:操作另一个类的方法的返回值 - Incompatible types error: Manipulating return value of another class's method 使用Kotlin和泛型进行数据绑定。 错误:类型不兼容:对象无法转换为列表 - Databinding with Kotlin and generics. error: incompatible types: Object cannot be converted to List 意外的奇怪错误 Kotlin “密封” class 与“何时”一起使用 - Unexpected Weird Error Kotlin “Sealed” class usage with 'when' Kotlin 中密封类层次结构的问题 - Problems with sealed class hierarchies in Kotlin 密封类内部的Kotlin数据类 - Kotlin dataclasses inside sealed class 我如何在Retrofit2中使用密封类作为返回类型 - How i can use sealed class as return type in Retrofit2 错误:不兼容的类型:int 无法转换为 String - error: incompatible types: int cannot be converted to String 错误:类型不兼容:Fragment 无法转换为 MapFragment - Error: incompatible types: Fragment cannot be converted to MapFragment 错误:类型不兼容:HomeFragment无法转换为上下文 - error: incompatible types: HomeFragment cannot be converted to Context
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM