Kotlintypes不匹配编译错误:需要成功,findMyError
我遇到了以下代码不能在kotlin中编译的问题。
// StateModel.kt sealed class StateModel class Loading : StateModel() data class Success(val data: T) : StateModel() data class MyError(val message: String) : StateModel() // StateModelTransformer.kt class StateModelTransformer : FlowableTransformer { override fun apply(upstream: Flowable): Publisher { return upstream .map { data -> Success(data) } .onErrorReturn { error -> MyError(error.message) // compile error, Type mismatch, Require Success, Found MyError } .startWith(Loading()) // compile error, none of the following function can be called with the arguments supplied } }
我不知道为什么onErrorReturn
说需要一个Success
types,但一个StateModel
types。
谢谢
以下是Flowable
中的相关声明,供参考。 让我们忽略onErrorReturn
; 这与这个问题没有关系。
public Flowable { public Flowable map(Function super T, ? extends R> mapper); public Flowable startWith(T value); }
这些是Kotlin推断的types。
val upstream: Flowable val mapper: (T) -> Success = { data -> Success(data) } val map: ((T) -> Success ) -> Flowable> = upstream::map val mapped: Flowable> = map(mapper) val loading: Loading = Loading() val startWith: (Success ) -> Flowable> = mapped::startWith startWith(loading) // type mismatch
更具体的Success
types已经被推断出来了,Kotlin不会回溯到find更一般的StateModel
types。 为了强制这种情况发生,例如,可以手动声明types
// be explicit about the general type of the mapper upstream.map { data -> Success(data) as StateModel }.startWith(Loading()) // be explicit about the generic type R = StateModel upstream.map { data -> Success(data) }.startWith(Loading())
顺便提一句,你现在在StateModel
输了
。 我建议改变基类以包含types参数。
sealed class StateModel object Loading : StateModel() data class Success(val data: T) : StateModel() data class MyError(val message: String) : StateModel()
这会让你写,例如,
val StateModel.data: T? get() = when (this) { is Success -> data else -> null }