
🧠 TL;DR:
If you’re using sealed interface + object in Kotlin and constructing a static listOf(...) from those objects — beware.
One of your objects might silently be null— 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? Partner was null?
🤯 Root Cause: Kotlin object is Lazy
Kotlin object declarations are lazily initialized — they only come alive when referenced.
So if Partner wasn’t accessed before values was initialized, it stayed null.
And
listOf(...)evaluated the reference — not the live object — which means you’re storingnull.
✅ 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
🧠 Why This Matters
- Kotlin
objects aren’t real singletons until you use them - Static lists capturing them too early may capture
null - 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 infuninstead of valwhen order matters.
This article was previously published on proandroiddev.com.


