Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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?

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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 = ...
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading