(Simple?) question? I want to create a generic sub...
# announcements
t
(Simple?) question? I want to create a generic subclass of RecyclerView.Adapter<RecyclerView.ViewHolder>. I tried:
Copy code
class FungibleRecyclerAdapter<T : RecyclerView.ViewHolder>():RecyclerView.Adapter<RecyclerView.ViewHolder>() {
   override fun onCreateViewHolder(parent:ViewGroup, viewType:Int):T {
      return RecyclerView.ViewHolder()
   }

   override fun getItemCount():Int {
      return 1
   }

   override fun onBindViewHolder(holder:T, position:Int) {
   }
}
I got a couple of errors: 1. It complains that FungibleRecyclerAdatper is not a proper subclass because it doesn’t implement all of the methods it should 2. It complains that it does not know what the return ViewHolder() is not what it wants, a T 3. It complains that the onBindViewHolder doesn’t override any method I can make a “normal” subclass of the Adapter where I specify a specific subclass of RecyclerView.ViewHolder if I want:
MyAdapter() : RecyclerView.Adapter<MyRowViewClass>() { … }
where
MyRowViewClass
is a subclass of
ViewHolder
just fine. But I wanted to make a generically pluggable one.
After much dart throwing, this seems to do the trick:
Copy code
class FungibleRecylerAdapter<T>():RecyclerView.Adapter<T>() where T : RecyclerView.ViewHolder { ... }
l
@Travis Griggs Wrong channel. Please remove from here and post in #C0B8M7BUY if you still want help from the Kotlin community
k
After much dart throwing, this seems to do the trick:
Copy code
class FungibleRecylerAdapter<T : RecyclerView.ViewHolder>():RecyclerView.Adapter<T>() { ... }
t
@louiscad I’m confused. Though the class I referenced was an Android class, it was purely arbitrary… The question was basically “given a generic class SuperClass<SuperClass.PrivateClass>, how do I create a generic subclass that allows the developer to express a T(ype) that is a subclass of SuperClass.PrivateClass?” Is it discouraged to post questions like that with placeholders that happen to be Android classes? I really wasn’t asking any question about Android behavior per se…
l
@Travis Griggs Well, reading your original question, you're asking how to create a subclass of an Android specific java abstract class. So Android knowledge is required. Anyway, you need to use
T
in the right hand side of the
:
in the class declaration.