{"id":1097,"date":"2026-11-29T13:46:00","date_gmt":"2026-11-29T12:46:00","guid":{"rendered":"https:\/\/grindloop.ai\/blog\/?p=1097"},"modified":"2026-11-28T18:22:53","modified_gmt":"2026-11-28T17:22:53","slug":"sealed-class-object-is-null","status":"publish","type":"post","link":"https:\/\/grindloop.ai\/blog\/sealed-class-object-is-null\/","title":{"rendered":"Sealed Class Object Is Null in a Kotlin Companion Object List: Why a Deep Link Crashes With NullPointerException"},"content":{"rendered":"<p>A sealed class object is null in a companion object list for one reason. A nested object was touched before the companion. Take <code>Screen.Settings<\/code>, a <code>data object<\/code> nested in <code>sealed class Screen<\/code>, with <code>val all = listOf(Home, Search, Settings)<\/code> in the companion. A deep link reads <code>Screen.Settings<\/code> first. The JVM must set up <code>Screen<\/code> before <code>Settings<\/code>, because <code>Screen<\/code> is its superclass. The companion&#8217;s list is built inside that setup. It reads <code>Settings.INSTANCE<\/code> while that field is still unassigned. So the list stores <code>null<\/code>. Kotlin checks nothing on that read. The crash comes later, at <code>it.route<\/code>, far from the cause. A cold start that reads <code>Screen.all<\/code> 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 <code>by lazy<\/code> or a getter.<\/p>\n\n<h2>The sealed class object is null after a deep link, so the route lookup crashes<\/h2>\n\n<p>An app keeps its destinations in one sealed class. The bottom bar and the route parser both use the companion&#8217;s <code>all<\/code> list. A notification opens the Settings screen. Its handler reads <code>Screen.Settings<\/code> before anything else touches <code>Screen<\/code>.<\/p>\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"kotlin\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">sealed class Screen(val route: String) {\n    data object Home : Screen(\"home\")\n    data object Search : Screen(\"search\")\n    data object Settings : Screen(\"settings\")\n\n    companion object {\n        val all: List&lt;Screen&gt; = listOf(Home, Search, Settings)\n        fun fromRoute(route: String): Screen =\n            all.firstOrNull { it.route == route } ?: Home\n    }\n}\n\nfun main(args: Array&lt;String&gt;) {\n    if (args.firstOrNull() == \"deeplink\") {\n        \/\/ The notification handler touches Settings first.\n        val start = Screen.Settings\n        println(\"start = $start\")\n    }\n    println(\"all = ${Screen.all}\")\n    println(Screen.fromRoute(args.getOrNull(1) ?: \"search\"))\n}<\/pre>\n\n\n<p>We compiled this with Kotlin 2.4.20 and ran it on the JVM twice. The first run reads <code>Screen.all<\/code> first, like a normal cold start. The second run reads <code>Screen.Settings<\/code> first, like the deep link. No Android APIs are involved.<\/p>\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">$ java -cp broken.jar BrokenKt cold settings\nall = [Home, Search, Settings]\nSettings\n\n$ java -cp broken.jar BrokenKt deeplink settings\nstart = Settings\nall = [Home, Search, null]\nException in thread \"main\" java.lang.NullPointerException: Cannot invoke \"Screen.getRoute()\" because \"it\" is null\n\tat Screen$Companion.fromRoute(broken.kt:9)<\/pre>\n\n\n<p>The same lookup for <code>\"search\"<\/code> passes on both runs. <code>firstOrNull<\/code> stops at <code>Search<\/code> before it reaches the null slot. So a test that only looks up the first routes stays green.<\/p>\n\n<h2>Initializing Settings first runs the Screen initializer, which builds the list<\/h2>\n\n<p>The first cause is JVM class initialization. The <a href=\"https:\/\/kotlinlang.org\/docs\/object-declarations.html\" target=\"_blank\" rel=\"noopener\">Kotlin docs on object declarations<\/a> 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 <code>all<\/code> belongs to <code>Screen<\/code> itself. The bytecode shows a static field on <code>Screen<\/code>, assigned in <code>Screen<\/code>&#8216;s own static initializer.<\/p>\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">\/\/ javap -c Screen, static {}\ngetstatic  Screen$Home.INSTANCE\ngetstatic  Screen$Search.INSTANCE\ngetstatic  Screen$Settings.INSTANCE\ninvokestatic CollectionsKt.listOf\nputstatic  Screen.all\n\n\/\/ javap -c Screen$Settings, static {}\nnew        Screen$Settings\ninvokespecial Screen$Settings.&lt;init&gt;\nputstatic  Screen$Settings.INSTANCE<\/pre>\n\n\n<p>The deep link reads <code>Settings.INSTANCE<\/code>, so the JVM starts to initialize <code>Settings<\/code>. The <a href=\"https:\/\/docs.oracle.com\/javase\/specs\/jls\/se21\/html\/jls-12.html#jls-12.4.2\" target=\"_blank\" rel=\"noopener\">Java Language Specification, section 12.4.2<\/a>, sets the order. Step 7 initializes the superclass first. Here that is <code>Screen<\/code>. The <code>Settings<\/code> initializer hasn&#8217;t run yet, so <code>INSTANCE<\/code> is still null. <code>Screen<\/code>&#8216;s initializer then reads <code>Settings.INSTANCE<\/code>. That read asks to initialize <code>Settings<\/code> again, on the same thread. Step 3 calls this a recursive request and returns at once. The read gets the field&#8217;s default value. For an object reference that is null.<\/p>\n\n<p>The cold start reverses the order. <code>Screen<\/code> starts first. Each <code>getstatic<\/code> then fully initializes <code>Home<\/code>, <code>Search<\/code> and <code>Settings<\/code> in turn. <code>Screen<\/code> 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 <code>A<\/code> first in <code>listOf(A, B)<\/code> gave <code>[null, B]<\/code>.<\/p>\n\n<h2>Kotlin trusts the object&#8217;s non-null type, so the null travels until it.route<\/h2>\n\n<p>The second cause is that nothing stops the null. An object reference has a non-null type, so the compiler adds no check on <code>getstatic<\/code>. <code>listOf<\/code> stores the null in a <code>List&lt;Screen&gt;<\/code> without complaint. The program only fails when code calls a member on that element. Here that is <code>it.route<\/code> inside <code>fromRoute<\/code>, far from the initializer that caused it.<\/p>\n\n<p>JetBrains has tracked this since August 2015 as <a href=\"https:\/\/youtrack.jetbrains.com\/issue\/KT-8970\" target=\"_blank\" rel=\"noopener\">KT-8970<\/a>. 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. <a href=\"https:\/\/youtrack.jetbrains.com\/issue\/KT-67222\" target=\"_blank\" rel=\"noopener\">KT-67222<\/a> 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.<\/p>\n\n<h2>Build the list on first use, after every object exists<\/h2>\n\n<p>Move the list out of <code>Screen<\/code>&#8216;s static initializer. With <code>by lazy<\/code>, the companion holds only a delegate. <code>listOf<\/code> runs on the first read of <code>all<\/code>. By then the deep link has finished initializing <code>Settings<\/code>.<\/p>\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"kotlin\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">sealed class Screen(val route: String) {\n    data object Home : Screen(\"home\")\n    data object Search : Screen(\"search\")\n    data object Settings : Screen(\"settings\")\n\n    companion object {\n        val all: List&lt;Screen&gt; by lazy { listOf(Home, Search, Settings) }\n        fun fromRoute(route: String): Screen =\n            all.firstOrNull { it.route == route } ?: Home\n    }\n}<\/pre>\n\n\n<p>We ran the same <code>main<\/code> against this version.<\/p>\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">$ java -cp fixed.jar FixedKt deeplink settings\nstart = Settings\nall = [Home, Search, Settings]\nSettings<\/pre>\n\n\n<p>A getter works too: <code>val all: List&lt;Screen&gt; get() = listOf(Home, Search, Settings)<\/code>. It gave the full list after a <code>Settings<\/code>-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&#8217;s own initializer may read <code>all<\/code>, or the cycle comes back.<\/p>\n\n<h2>The interview answer traces the crash back to the first read of Settings<\/h2>\n\n<p>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.<\/p>\n\n<ol>\n<li>Point at the message. <code>it<\/code> is null inside a <code>List&lt;Screen&gt;<\/code>, so a non-null object slot holds null.<\/li>\n<li>Name the first cause. Reading <code>Settings<\/code> first makes the JVM initialize <code>Screen<\/code> first, because it&#8217;s the superclass.<\/li>\n<li>Say where the list lives. The companion&#8217;s <code>val<\/code> is a static field set in <code>Screen<\/code>&#8216;s static initializer.<\/li>\n<li>Name the recursion. That initializer reads <code>Settings.INSTANCE<\/code> while <code>Settings<\/code> is mid-initialization on the same thread. JLS 12.4.2 returns at once, so the read is null.<\/li>\n<li>Name the second cause. Kotlin adds no null check on object reads, so the null reaches <code>it.route<\/code>.<\/li>\n<li>Explain why tests missed it. Cold start reads <code>Screen.all<\/code> first, so only the deep link path breaks.<\/li>\n<li>Give the fix. Build the list with <code>by lazy<\/code> or a getter. Cite KT-8970 as the known open issue.<\/li>\n<\/ol>\n\n<p>Step 6 proves you ran both entry paths. Finding the first bug doesn&#8217;t end that round. Hass covers why in <a href=\"https:\/\/grindloop.ai\/blog\/android-debugging-interview-second-bug\/\">the Android debugging interview<\/a>. Constructor order causes a related bug. We covered it in our post on <a href=\"https:\/\/grindloop.ai\/blog\/non-null-kotlin-property-is-null\/\">a non-null Kotlin property that is null<\/a>.<\/p>\n\n<h2>Reordering, filtering and locking all leave the cycle in place<\/h2>\n\n<p>&#8220;Declare the companion above the objects.&#8221; Source order doesn&#8217;t change the class that starts first. We moved the companion to the top of the class and read <code>Settings<\/code> first. The list still came back as <code>[Home, null]<\/code>.<\/p>\n\n<p>&#8220;Add <code>filterNotNull()<\/code> to the list.&#8221; The crash goes away. So does Settings. In our run the list held only <code>[Home]<\/code>. <code>fromRoute(\"settings\")<\/code> then fell back to <code>Home<\/code>. The deep link opens the wrong screen with nothing in the log.<\/p>\n\n<p>&#8220;It&#8217;s a race, so add <code>@Synchronized<\/code> or a lock.&#8221; 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&#8217;t change the JVM&#8217;s initialization order.<\/p>\n\n<p>&#8220;It&#8217;s a Kotlin compiler bug, so upgrade.&#8221; 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.<\/p>\n","protected":false},"excerpt":{"rendered":"<p>A sealed class object is null in a companion list when a nested object loads first. Why JVM init order does it, a deep link NPE repro and the by lazy fix.<\/p>\n","protected":false},"author":2,"featured_media":1098,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"rank_math_title":"Sealed Class Object Is Null in a Kotlin Companion Object List: Why a Deep Link Crashes With NullPointerException","rank_math_description":"A sealed class object is null in a companion list when a nested object loads first. Why JVM init order does it, a deep link NPE repro and the by lazy fix.","rank_math_focus_keyword":"sealed class object is null","footnotes":""},"categories":[9,2],"tags":[15,87,16,12,98,123,45],"class_list":["post-1097","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-bug-squash","category-kotlin","tag-android","tag-debugging-interview","tag-interview-prep","tag-kotlin","tag-null-safety","tag-sealed-classes","tag-technical-interview"],"_links":{"self":[{"href":"https:\/\/grindloop.ai\/blog\/wp-json\/wp\/v2\/posts\/1097","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/grindloop.ai\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/grindloop.ai\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/grindloop.ai\/blog\/wp-json\/wp\/v2\/users\/2"}],"replies":[{"embeddable":true,"href":"https:\/\/grindloop.ai\/blog\/wp-json\/wp\/v2\/comments?post=1097"}],"version-history":[{"count":1,"href":"https:\/\/grindloop.ai\/blog\/wp-json\/wp\/v2\/posts\/1097\/revisions"}],"predecessor-version":[{"id":1099,"href":"https:\/\/grindloop.ai\/blog\/wp-json\/wp\/v2\/posts\/1097\/revisions\/1099"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/grindloop.ai\/blog\/wp-json\/wp\/v2\/media\/1098"}],"wp:attachment":[{"href":"https:\/\/grindloop.ai\/blog\/wp-json\/wp\/v2\/media?parent=1097"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/grindloop.ai\/blog\/wp-json\/wp\/v2\/categories?post=1097"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/grindloop.ai\/blog\/wp-json\/wp\/v2\/tags?post=1097"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}