Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to safely cast (no null cast) in Kotlin

Tags:

kotlin

    for (i in position until effectList.size) {
        var holder = mRecyclerView.findViewHolderForAdapterPosition(i) as EffectsHolder
        holder.bindEffect(holder.effect, i)
    }

My code is causing a null pointer cast like this:

kotlin.TypeCastException: null cannot be cast to non-null type com.mobileer.androidfxlab.EffectsAdapter.EffectsHolder

Because mRecyclerView.findViewHolderForAdapterPosition(i) returns null. How can I conditionally cast only if mRecyclerView.findViewHolderForAdapterPosition(i) is not null? Then I can do holder?.bindEffect(holder.effect, i)

like image 578
Guerlando OCs Avatar asked Sep 10 '25 16:09

Guerlando OCs


1 Answers

Kotlin allows you to perform a cast like this using the Safe (nullable) Cast Operator:

val maybeString: String? = someObject as? String

So in your case, perhaps something like this:

var holder = mRecyclerView.findViewHolderForAdapterPosition(i) as? EffectsHolder
holder?.bindEffect(holder?.effect, i)
like image 160
Todd Avatar answered Sep 13 '25 11:09

Todd