user17027702
user17027702

Reputation:

Android Kotlin - check if type can be casted

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?

Upvotes: 1

Views: 724

Answers (3)

Ma3x
Ma3x

Reputation: 6549

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 = ...
}

Upvotes: 2

Noah
Noah

Reputation: 3425

Use as? instead of as to either get the casted value, or null, if casting is unsuccessful.

Upvotes: 0

snachmsm
snachmsm

Reputation: 19223

try this before casting with as keyword

if (holder is MemesAdapter.ViewHolder)

is is crucial in here ;)

Upvotes: 0

Related Questions