Home > Net >  Android Kotlin - check if type can be casted
Android Kotlin - check if type can be casted

Time:01-08

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?

CodePudding user response:

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

CodePudding user response:

try this before casting with as keyword

if (holder is MemesAdapter.ViewHolder)

is is crucial in here ;)

CodePudding user response:

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

  •  Tags:  
  • Related