Sealed Class Object Is Null in a Kotlin Companion Object List: Why a Deep Link Crashes With NullPointerException

A sealed class object is null in a companion object list for one reason. A nested object was touched before the companion. Take Screen.Settings, a data object nested in sealed class Screen, with val all = listOf(Home, Search, Settings) in the companion. A deep link reads Screen.Settings first. The JVM must set up Screen before Settings, because Screen is its superclass. The companion’s list is built inside that setup. It reads Settings.INSTANCE while that field is still unassigned. So the list stores null. Kotlin checks nothing on that read. The crash comes later, at it.route, far from the cause. A cold start that reads Screen.all first never fails. The bug has two causes. The superclass is initialized before the subclass. Kotlin also trusts the non-null type of an object reference. The fix is to build the list on first use, with by lazy or a getter.

The sealed class object is null after a deep link, so the route lookup crashes

An app keeps its destinations in one sealed class. The bottom bar and the route parser both use the companion’s all list. A notification opens the Settings screen. Its handler reads Screen.Settings before anything else touches Screen.

sealed class Screen(val route: String) {
    data object Home : Screen("home")
    data object Search : Screen("search")
    data object Settings : Screen("settings")

    companion object {
        val all: List<Screen> = listOf(Home, Search, Settings)
        fun fromRoute(route: String): Screen =
            all.firstOrNull { it.route == route } ?: Home
    }
}

fun main(args: Array<String>) {
    if (args.firstOrNull() == "deeplink") {
        // The notification handler touches Settings first.
        val start = Screen.Settings
        println("start = $start")
    }
    println("all = ${Screen.all}")
    println(Screen.fromRoute(args.getOrNull(1) ?: "search"))
}

We compiled this with Kotlin 2.4.20 and ran it on the JVM twice. The first run reads Screen.all first, like a normal cold start. The second run reads Screen.Settings first, like the deep link. No Android APIs are involved.

$ java -cp broken.jar BrokenKt cold settings
all = [Home, Search, Settings]
Settings

$ java -cp broken.jar BrokenKt deeplink settings
start = Settings
all = [Home, Search, null]
Exception in thread "main" java.lang.NullPointerException: Cannot invoke "Screen.getRoute()" because "it" is null
	at Screen$Companion.fromRoute(broken.kt:9)

The same lookup for "search" passes on both runs. firstOrNull stops at Search before it reaches the null slot. So a test that only looks up the first routes stays green.

Initializing Settings first runs the Screen initializer, which builds the list

The first cause is JVM class initialization. The Kotlin docs on object declarations say an object is initialized lazily, on first access. They also say a companion object is initialized when its containing class is loaded. That matches a Java static initializer. So all belongs to Screen itself. The bytecode shows a static field on Screen, assigned in Screen‘s own static initializer.

// javap -c Screen, static {}
getstatic  Screen$Home.INSTANCE
getstatic  Screen$Search.INSTANCE
getstatic  Screen$Settings.INSTANCE
invokestatic CollectionsKt.listOf
putstatic  Screen.all

// javap -c Screen$Settings, static {}
new        Screen$Settings
invokespecial Screen$Settings.<init>
putstatic  Screen$Settings.INSTANCE

The deep link reads Settings.INSTANCE, so the JVM starts to initialize Settings. The Java Language Specification, section 12.4.2, sets the order. Step 7 initializes the superclass first. Here that is Screen. The Settings initializer hasn’t run yet, so INSTANCE is still null. Screen‘s initializer then reads Settings.INSTANCE. That read asks to initialize Settings again, on the same thread. Step 3 calls this a recursive request and returns at once. The read gets the field’s default value. For an object reference that is null.

The cold start reverses the order. Screen starts first. Each getstatic then fully initializes Home, Search and Settings in turn. Screen is already in progress on that thread, so their superclass step returns at once. Every slot gets a real object. Which slot goes null depends only on which object the app touches first. In a smaller script, reading A first in listOf(A, B) gave [null, B].

Kotlin trusts the object’s non-null type, so the null travels until it.route

The second cause is that nothing stops the null. An object reference has a non-null type, so the compiler adds no check on getstatic. listOf stores the null in a List<Screen> without complaint. The program only fails when code calls a member on that element. Here that is it.route inside fromRoute, far from the initializer that caused it.

JetBrains has tracked this since August 2015 as KT-8970. Its title says an object reads as null from a static context during an initialization loop. A companion object is the example it names. The reporter asked for an exception in place of the silent null. The issue is still open. KT-67222 was filed in April 2024 and is also open. It reports the same null with a sealed route class and a companion list. So neither the compiler nor the runtime will warn you today.

Build the list on first use, after every object exists

Move the list out of Screen‘s static initializer. With by lazy, the companion holds only a delegate. listOf runs on the first read of all. By then the deep link has finished initializing Settings.

sealed class Screen(val route: String) {
    data object Home : Screen("home")
    data object Search : Screen("search")
    data object Settings : Screen("settings")

    companion object {
        val all: List<Screen> by lazy { listOf(Home, Search, Settings) }
        fun fromRoute(route: String): Screen =
            all.firstOrNull { it.route == route } ?: Home
    }
}

We ran the same main against this version.

$ java -cp fixed.jar FixedKt deeplink settings
start = Settings
all = [Home, Search, Settings]
Settings

A getter works too: val all: List<Screen> get() = listOf(Home, Search, Settings). It gave the full list after a Settings-first read in our run. It builds a new list on every call. For three items that costs very little. Either way, one rule still holds. Nothing in an object’s own initializer may read all, or the cycle comes back.

The interview answer traces the crash back to the first read of Settings

The round may hand you the crash log and the sealed class. The bug only shows on one entry path. Start at the null and work back to the read that came first.

  1. Point at the message. it is null inside a List<Screen>, so a non-null object slot holds null.
  2. Name the first cause. Reading Settings first makes the JVM initialize Screen first, because it’s the superclass.
  3. Say where the list lives. The companion’s val is a static field set in Screen‘s static initializer.
  4. Name the recursion. That initializer reads Settings.INSTANCE while Settings is mid-initialization on the same thread. JLS 12.4.2 returns at once, so the read is null.
  5. Name the second cause. Kotlin adds no null check on object reads, so the null reaches it.route.
  6. Explain why tests missed it. Cold start reads Screen.all first, so only the deep link path breaks.
  7. Give the fix. Build the list with by lazy or a getter. Cite KT-8970 as the known open issue.

Step 6 proves you ran both entry paths. Finding the first bug doesn’t end that round. Hass covers why in the Android debugging interview. Constructor order causes a related bug. We covered it in our post on a non-null Kotlin property that is null.

Reordering, filtering and locking all leave the cycle in place

“Declare the companion above the objects.” Source order doesn’t change the class that starts first. We moved the companion to the top of the class and read Settings first. The list still came back as [Home, null].

“Add filterNotNull() to the list.” The crash goes away. So does Settings. In our run the list held only [Home]. fromRoute("settings") then fell back to Home. The deep link opens the wrong screen with nothing in the log.

“It’s a race, so add @Synchronized or a lock.” Every run above used one thread. The null comes from a recursive request on that one thread. Step 3 of JLS 12.4.2 lets it through. A lock in your code doesn’t change the JVM’s initialization order.

“It’s a Kotlin compiler bug, so upgrade.” KT-8970 and KT-67222 are both still open. Our repro failed on Kotlin 2.4.20. The rules that cause it belong to the JVM. The KT-67222 reporter rebuilt the same null in plain Java.

Leave a Comment