val holder: MemesAdapter.ViewHolder? = binding.contentMain.recyclerViewMemes.findViewHolderForAdapterPosition(i) as MemesAdapter.ViewHolder?
Sometimes it can’t be casted, it would be workaround to prevent the crash so is there a way to check it beforehand?
>Solution :
There is a way to check types before casting them
Option 1: using is
val holder = binding.contentMain.recyclerViewMemes
.findViewHolderForAdapterPosition(i)
if (holder is MemesAdapter.ViewHolder) {
// cast is possible, and you don't need to cast it manually
// because Kotlin smart-cast will do it for you
// holder is already of type MemesAdapter.ViewHolder inside this if
holder.someProperty = ...
}
Option 2: using as? (with the question mark)
val holder = binding.contentMain.recyclerViewMemes
.findViewHolderForAdapterPosition(i) as? MemesAdapter.ViewHolder
if (holder != null) {
// cast succeeded and Kotlin smart-cast ensures
// it is of type MemesAdapter.ViewHolder (not null!) inside this if
holder.someProperty = ...
}
The first option (using is) has the advantage if you have to check for more than just one type (in heterogenous adapters), for example
val holder = binding.contentMain.recyclerViewMemes
.findViewHolderForAdapterPosition(i)
if (holder is MemesAdapter.HeaderViewHolder) {
holder.someHeaderProperty = ...
} else if (holder is MemesAdapter.ItemViewHolder) {
holder.someItemProperty = ...
}