gpt4 book ai didi

android - Kotlin 泛型方法和继承

转载 作者:行者123 更新时间:2023-11-29 14:37:05 29 4
gpt4 key购买 nike

在我的代码中,我想在抽象类中创建一个方法,它返回一些 Observable。然后这个抽象类的实现将返回特定(指定)类型的 Observable。不幸的是,Android Studio 将在实现方法()中返回错误“类型不匹配”:

  • 预期:可观察
  • 找到:Observable<{package}.DrawerItemEntity>

我的 MockDrawerList.getList()返回 Observable<DrawerItemEntity>

请关注execute()buildUseCaseObservable

抽象类

public abstract class UseCase(threadExecutor: ThreadExecutor,
postExecutionThread: PostExecutionThread) {

private val threadExecutor: ThreadExecutor
private val postExecutionThread: PostExecutionThread

private var subscription: Subscription = Subscriptions.empty()

init {
this.postExecutionThread = postExecutionThread
this.threadExecutor = threadExecutor
}

protected abstract fun buildUseCaseObservable(): Observable<Any>

public fun execute(useCaseSubsriber: Subscriber<Any>) {
subscription = buildUseCaseObservable()
.subscribeOn(Schedulers.from(threadExecutor))
.observeOn(postExecutionThread.getScheduler())
.subscribe(useCaseSubsriber)
}

public fun unsubsribe() {
if (!subscription.isUnsubscribed())
subscription.unsubscribe()
}
}

实现

Inject
class GetDrawerListUseCase(threadExecutor: ThreadExecutor,
postExecutionThread:PostExecutionThread) : UseCase(threadExecutor, postExecutionThread) {

override fun buildUseCaseObservable(): Observable<Any> {
return MockDrawerList.getList()
}
}

最佳答案

尽管StringAny 的子类型, Observable<String> 被视为 Observable<Any> 的子类型在 Kotlin 。你应该使用use-site variance:改变buildUseCaseObservable的返回类型为 Observable<out Any>Observable<*> (后者相当于 Observable<out Any?> )并且代码应该可以编译。

为什么泛型类型的继承不能根据它们的类型参数自动工作?这是 Joshua Bloch 在 Effective Java,Item 28:Use bounded wildcards to increase API flexibility 中最好解释的问题。简而言之,这只有在保证类型不使用其类型参数的实例时才有效,即如果一个类具有通用参数 T没有采取 T 的方法作为参数。在 Kotlin 中可以强制执行的一种方法是 declaration-site variance ,例如集合接口(interface)( kotlin.Collection , kotlin.List , ...)就是这种情况。

然而,Observable这当然不是 Kotlin 类,所以编译器无法知道 Observable<String>可以在 Observable<Any> 的地方安全使用是期待。所以我们必须手动告诉编译器我们可以只使用 Observable<T> 的一部分功能。不需要 T作为参数,这样我们就可以得到很好的继承。此“子集类型”称为 type projection在 Kotlin 中,该技术称为使用位置差异。

您可以在官方语言文档 Generics 部分阅读更多关于 Kotlin 中声明和使用位置差异的信息.

关于android - Kotlin 泛型方法和继承,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31641915/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com