Poperton
Poperton

Reputation: 2127

How to safely cast (no null cast) in 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)

Upvotes: 4

Views: 2241

Answers (2)

Animesh Sahu
Animesh Sahu

Reputation: 8096

While Kotlin provides a safe cast operator as? but you still need to handle the nulls and if you look at the bytecode, as? has more instructions.

So what I recommend is to use the is operator as most as possible. It does not do internal casting in the JVM, instead only checks for it and the object is actually smart-casted to the cheched type.

Example:

val holder = mRecyclerView.findViewHolderForAdapterPosition(i)
if (holder is EffectsHolder) {
    // use `holder` here, it is smart-casted internally into EffectsHolder
}

Upvotes: 2

Todd
Todd

Reputation: 31660

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)

Upvotes: 3

Related Questions