Interface vs abstract class vs class problem

I’m implementing Android RecyclerView with three different ViewHolders.

  1. RecyclerView's Adapter needs to implement three functions, among them fun onCreateViewHolder(parent: ViewGroup, type: Int): ViewHolder where the returning ViewHolder must be a RecyclerView.ViewHolder or its child.

  2. Each ViewHolder has a few properties that are common for each of them. Like ImageViews and Buttons. They also must have their own implementation to some common functions (mainly bind() that will be called in RecyclerView's onBindViewHolder()).

My question: how do I extract those common ViewHolder fields?

  1. interface - cannot store state unless it’s abstract or with provided get() implementation. But I cannot call findViewById( in the interface
  2. abstract class - cannot be instantiated, that’s problematic with requirement 1.
  3. class - works but it should never be instantiated, only its children.

By process of elimination, the individual ViewHolders use both interface (abstract functions) and a class (common properties). Is there a more elegant solution?

You can either have an abstract val view that they must implement, and then call findViewById on that. Alternatively, you can have them implement a findViewById function on the interface.

1 Like