3
    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)

Guerlando OCs
  • 1,886
  • 9
  • 61
  • 150
  • 2
    You could also do `as? EffectsHolder` which will return null if the object is anything else than an `EffectsHolder`. – marstran May 24 '20 at 20:44

2 Answers2

1

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)
Todd
  • 30,472
  • 11
  • 81
  • 89
1

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
}
Animesh Sahu
  • 7,445
  • 2
  • 21
  • 49