我对泛型类型、子类型和它们之间的不匹配有疑问。我有特定的结构类和接口。我会告诉你,请解释为什么会发生类型不匹配。
假设我正在准备我的 MVP 框架,并且我有以下接口和类:
这是最高的抽象
interface Presenter<in V : AbstractView> {
fun attachView(view: V)
fun detachView()
fun onDestory() {
}
}
抽象类包含Presenter的具体方法和实现
abstract class AbstractPresenter<V : AbstractView> : Presenter<V>, LifecycleObserver {
private var viewReference: WeakReference<V?>? = null
protected abstract fun onAttached(view: V)
final override fun attachView(view: V) {
viewReference = WeakReference(view)
onAttached(view)
}
final override fun detachView() {
viewReference?.clear()
viewReference = null
onDetached()
}
protected open fun onDetached() {
}
}
合同
interface DashboardContract {
interface View : AbstractView {
}
abstract class Presenter : AbstractPresenter<View>(){
}
}
最后
class DashboardPresenter : DashboardContract.Presenter() {
override fun onAttached(view: DashboardContract.View) {
}
}
就它而言,AbstractView
它看起来更简单。只有界面AbstractView
。在合同中DashboardContract.View
扩展AbstractView
了接口,我DashboardActivity
实现了这个DashboardContract.View
接口。
class DashboardActivity : BaseActivity(), DashboardContract.View { ... }
所以当我在我的和创建方法中创建DashboardPresenter
一个属性时,我得到了为什么?不是 的子类型吗?DashboardActivity
fun getPresenter() : Presenter<AbstractView>
Type mismatch error
Presenter<AbstractView>
fun getPresenter() : AbstractPresenter<AbstractView> {
return dashboardPresenter // The type is DashboardPresenter
}
让我们看一下Java代码:
我正在看反编译 Kotlin 的 Java 代码。我把它放在下面。这是看起来的Presenter
样子:
public interface Presenter {
void attachView(@NotNull AbstractView var1);
void detachView();
void onDestory();
@Metadata(...)
public static final class DefaultImpls {
public static void onDestory(Presenter $this) {
}
}
}
我认为如果我在 Kotlin 中使用泛型类,我也会在 java 中获得泛型类。我错了。
AbstractPresenter
给出:
public abstract class AbstractPresenter implements Presenter, LifecycleObserver {
private WeakReference viewReference;
protected abstract void onAttached(@NotNull AbstractView var1);
public final void attachView(@NotNull AbstractView view) {
Intrinsics.checkParameterIsNotNull(view, "view");
this.viewReference = new WeakReference(view);
this.onAttached(view);
}
public final void detachView() {
WeakReference var10000 = this.viewReference;
if(this.viewReference != null) {
var10000.clear();
}
this.viewReference = (WeakReference)null;
this.onDetached();
}
protected void onDetached() {
}
public void onDestory() {
DefaultImpls.onDestory(this);
}
}
合同
public interface DashboardContract {
@Metadata(...)
public interface View extends AbstractView {
}
@Metadata(...)
public abstract static class Presenter extends AbstractPresenter {
}
}
DashboardPresetner
:_
public final class DashboardPresenter extends Presenter {
protected void onAttached(@NotNull View view) {
Intrinsics.checkParameterIsNotNull(view, "view");
}
// $FF: synthetic method
// $FF: bridge method
public void onAttached(AbstractView var1) {
this.onAttached((View)var1);
}
}