Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Extending generic class in Kotlin

Lets say that I have this sample code in Java:

public class MyActivityDelegate implements ActivityMvpDelegate

where ActivityMvpDelegate:

interface ActivityMvpDelegate<V extends MvpView, P extends MvpPresenter<V>>

Same code converted to Kotlin looks like this

class MyActivityDelegate(private val activity: Activity) : ActivityMvpDelegate<MvpView, MvpPresenter<V>>

Of course I got unresolved reference at V and I'm not sure how this code should looks, in Java I don't have to specify generic over here.. any tips gonna be much appreciated

like image 866
henorek Avatar asked Jun 08 '16 21:06

henorek


1 Answers

Your interface declaration requires that

  • V extends MvpView
  • V (exactly V, not its subtype) is used as generic parameter for P extends MvpPresenter<V>

Given that, you cannot extend ActivityMvpDelegate<MvpView, MvpPresenter<V>>, because there's no guarantee that V is exactly MvpView (also, in Kotlin, generic parameters are not implicitly inherited, you have to redeclarate them like class SomeClass<T> : SomeInterface<T>).

You can, however, write it as

class MyActivityDelegate(private val activity: Activity) 
: ActivityMvpDelegate<MvpView, MvpPresenter<MvpView>>

or introduce another generic parameter, so that V and the argument for P are still the same:

class MyActivityDelegate<T : MvpView>(private val activity: Activity) 
: ActivityMvpDelegate<T, MvpPresenter<T>>

You can also change the generic declaration of your interface from P extends MvpPresenter<V> to P extends MvpPresenter<? extends V> (or use out V in Kotlin), and you will be able to use any subtype of V as the argument, including bounded generic:

class MyActivityDelegate<T : MvpView>(private val activity: Activity) 
: ActivityMvpDelegate<MvpView, MvpPresenter<T>>
like image 167
hotkey Avatar answered Sep 27 '22 21:09

hotkey