问一个泛型类继承问题


#1

abstract class BasePresenter<V : ViewInterface> : PresenterInterface<V> {

/**
使用弱引用来防止内存泄漏
/
private var wrf: WeakReference<V>? = null

override fun attachView(view: V) {
wrf = WeakReference(view)
}

@Throws(Exception::class)
override fun getView(): V? {
return wrf?.get()
}

override fun detachView() {
if (wrf != null) {
wrf?.clear()
wrf = null
}
}

}

abstract class BaseActivity<P : BasePresenter<*>> : AppCompatActivity(), ViewInterface {

var presenter: P? = null
var mNextRequestPage = 1
var PAGE_SIZE = 10

protected abstract val layoutId: Int

override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(layoutId)
setPresenter()
if (presenter != null) {
presenter!!.attachView(this)
}
}
}

这个baseActivity里面要怎么写


#2

需要通过递归来实现绑定,当类型参数为<*>表示的是一个Nothing,即没有类型绑定,无法使用任何带泛型参数的方法,因为缺少返回类型

interface View<V : View<V, P>, P : Presenter<V, P>> {

    fun p(p: P)
}

interface Presenter<V : View<V, P>, P : Presenter<V, P>> {

    fun v(v: V)
}

class BaseView : View<BaseView, BasePresenter> {

    override fun p(p: BasePresenter) {
        p.v(this)
    }

}

class BasePresenter : Presenter<BaseView, BasePresenter> {
    
    override fun v(v: BaseView) {
       v.p(this)
    }

}

京ICP备16022265号-2 Kotlin China 2017 - 2018