Johnny Blade
Johnny Blade

Reputation: 27

Why RecyclerView Adapter is a generic class

Class signature is RecyclerView.Adapter<"VH extends android.support.v7.widget.RecyclerView.ViewHolder">. VH type is bounded by RecyclerView.ViewHolder.

As RecyclerView.ViewHolder is an abstract class, any instance of VH is inherited by RecyclerView.ViewHolder.

For example onCreateViewHolder method returns the generic VH type object, which is inherited from RecyclerView.ViewHolder in any case. So why don't just make RecyclerView.ViewHolder as a return type (instead of VH generic type) and make all this stuff without generic style?

Upvotes: 1

Views: 1365

Answers (1)

payloc91
payloc91

Reputation: 3809

Because you want your subclass of RecyclerView.Adapter to deal only with a particular ViewHolder type.

This is why the class signature allows you to specify a VH type. So that the class will be modeled after your needs; the methods onBindViewHolder, onCreateViewHolder will be adapted to deal only with your preferred ViewHolder sub-type.

Without generics, (the methods mentioned above would have ViewHolder rather than the generic VH type), you could return SubViewHolder1 from onCreateViewHolder and try to cast the first parameter of onBindViewHolder to SubViewHolder2 (and you would get a ClassCastException). Not that you would do it, but the code is allowing you do it. So why not set some constraints that would ease your life?

By taking advantage of the generic type, you are saying:

This is my Adapter for a RecyclerView. This Adapter deals with only this ViewHolder sub-class. Nothing else.

Upvotes: 2

Related Questions