Why does the compiler give me the error `TypeMisma...
# announcements
k
Why does the compiler give me the error
TypeMismatch
in the
onCreateViewHolder
for both branches of the
when
? Return type is listed as the sealed class
BaseHolder<PossibleRow>
and the return types are both subclasses of the sealed class.
Copy code
sealed class PossibleRow { /* objects A, B defined here */ }

sealed class BaseHolder<T: PossibleRow>(...): RecyclerView.ViewHolder(...) {
  class AHolder(...): BaseHolder<PossibleRow.A>(...)
  class BHolder(...): BaseHolder<PossibleRow.B>(...)
}

class LiftGroupRowAdapter {
  override fun onCreateViewHolder(..., viewType: Int): BaseHolder<PossibleRow> {
    return when(viewType) {
      0 -> BaseHolder.AHolder(...)
      1 -> BaseHolder.BHolder(...)
      else -> throw IllegalStateException("invalid viewType")
    }
  }
}
j
override fun onCreateViewHolder(..., viewType: Int): BaseHolder<out PossibleRow>
???
Change the return type to
BaseHolder<out PossibleRow>
?
k
Thanks. That got me almost there.
Copy code
override fun onBindViewHolder(holder: BaseHolder<out PossibleRow>, position: Int) {
    holder.bind(sets[position])
  }
Err, it did not have the
out
. I had to add the
out
in the parameter signature. Then I had to update the function to be:
Copy code
override fun onBindViewHolder(holder: BaseHolder<out PossibleRow>, position: Int) {
    when(holder) {
      is BaseHolder.AHolder -> holder.bind(sets[position] as PossibleRow.A)
      is BaseHolder.BHolder -> holder.bind(sets[position] as PossibleRow.B)
    }
  }
I can’t imagine why the
out
is needed, though. 😕