user3145736
user3145736

Reputation: 11

Kotlin, define object with class type that extends generic

I've got MVP realization that I try to convert in Kotlin, but I am stuck with generics - I failed in instantiating object with unknown type that extends parent presenter class. I've got interface for presenters:

interface BasePresenter {
    fun attachView(view: View)
    fun detachView(view: View)
...}

And some basic code for fragment that will have presenter. In java it works this way:

abstract public class BaseFragmentWithPresenter<P extends BasePresenter> extends BaseFragment {
    @Inject
    protected P presenter;

As you can see, in this parent class I use Dagger 2 for presenter injection, and I also predefine some logic here:

public void onViewCreated(...) {
    super.onViewCreated(view, savedInstanceState);
    presenter.attachView(this);
}

How to do this in Kotlin? I read about in\out technics but still failed.

Upvotes: 1

Views: 296

Answers (2)

user3145736
user3145736

Reputation: 11

I found that Kotlin is much more heavy with generics rather than Java. I came across with this solution:

abstract class BaseFragmentWithPresenter<V : BaseView, P : BasePresenter<V>> : BaseFragment() {

override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
    super.onViewCreated(view, savedInstanceState)
    presenter.attachView(this as V)
}

Upvotes: 0

Birju Vachhani
Birju Vachhani

Reputation: 6373

Try this:

abstract class BaseFragmentWithPresenter<P : BasePresenter> : BaseFragment() {
    protected abstract val presenter: P
}

Upvotes: 0

Related Questions