Blog Infos
Author
Published
Topics
, , , ,
Author
Published

🧠 TL;DR:

If you’re using  in Kotlin and constructing a static  from those objects — beware.
One of your objects might silently be — if it wasn’t accessed before the list was created. 🤯

🐛 The Bug

I had this clean sealed interface setup:

internal sealed interface StaffRoleOption {
    object Partner : StaffRoleOption
    object Salesman : StaffRoleOption
    object StockManager : StaffRoleOption
    object DeliveryBoy : StaffRoleOption

    companion object {
        val values = listOf(Partner, Salesman, StockManager, DeliveryBoy)
    }
}

Looked fine. Worked great… until it didn’t.
In my RecyclerView adapter:

StaffRoleOption.values[position]  // 😵 Partner was null

Debugging showed this:

values = [null, Salesman, StockManager, DeliveryBoy]

Wait… what?  was null?

🤯 Root Cause: Kotlin  is Lazy

Kotlin  declarations are lazily initialized — they only come alive when referenced.
So if  wasn’t accessed before  was initialized, it stayed null.

And  evaluated the reference — not the live object — which means you’re storing .

✅ The Fix

💡 Wrap your list in a function to defer resolution until runtime:

companion object {
    fun values(): List<StaffRoleOption> = listOf(Partner, Salesman, StockManager, DeliveryBoy)
}

// Then access it like:
StaffRoleOption.values()[position] // Boom — no more phantom nulls. 🎯

Job Offers

Job Offers

There are currently no vacancies.

OUR VIDEO RECOMMENDATION

No results found.

Jobs

🧠 Why This Matters
  • Kotlin s aren’t real singletons until you use them
  • Static lists capturing them too early may capture 
  • No warning. No crash (unless you dereference it)
  • Easy to miss — especially if it “usually works”
📚 Lesson Learned

Never assume Kotlinobjectinstances exist just because they’re declared.
Wrap lazy references like these in
funinstead of valwhen order matters.

This article was previously published on proandroiddev.com.

Menu