我有一个问题,无法解决。我有一个接口(interface) Presenter
这是通用的,采用接口(interface)的任何子类型 MvpView
interface Presenter<in V : MvpView> {
fun attachView(view: V)
fun detachView()
}
那我还有一个
抽象类 BasePresenter
这是 Presenter
的子类型
abstract class BasePresenter<V : MvpView> : Presenter<V> {
protected var mvpView: V? = null
protected get
override fun attachView(view: V) {
this.mvpView = view
}
override fun detachView() {
mvpView = null
}
}
我有课
abstract class BaseMvpActivity<P : BasePresenter<T>, T : MvpView> : BaseActivity(), MvpView {
@Inject lateinit protected var presenter: P
protected abstract fun inject()
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
inject()
initPresenter(savedInstanceState)
}
protected fun initPresenter(savedInstanceState: Bundle?) {
presenter.attachView(this)
}
override fun onDestroy() {
presenter.detachView()
super.onDestroy()
}
}
尝试调用 presenter.attachView(this)
时出现错误
Type mismatch: inferred type is BaseMvpActivity<P, T> but T was expected
我也试过这样做abstract class BaseMvpActivity<P : BasePresenter<*>> : BaseActivity()
但也有类似 Type mismatch: inferred type is BaseMvpActivity<P> but Nothing was expected
的错误
我该如何解决这个问题?谢谢。
最佳答案
为什么要使 BasePresetner
成为泛型,因为您不会返回该泛型类型的值。我们使用泛型来防止方法返回值的类型转换,并防止可能的 Cast 异常。
我想说的是您不需要使 BasePresenter
通用。只需将 mvpView 声明为 MvpView 并使用其方法即可。假设如果你确实让它成为通用的,你将不会获得任何加分,因为你仍然只能访问 MvpView 的方法(不是 子类
)。
abstract class BasePresenter : Presenter<V> {
protected var mvpView: MvpView = null
protected get
override fun attachView(view: MvpView) {
this.mvpView = view
}
override fun detachView() {
mvpView = null
}
}
希望对您有所帮助。
关于generics - Kotlin 泛型继承,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44213931/