Kotlin Companion Object List NPE when called from another companion object fun - works when list is statically initialized outside of the class?

Viewed 43

So I have two examples for you.

The one that crashes with a NPE is this:

https://pl.kotl.in/Do3nHlv1S

fun main() {
   
    val instance = Test.First
    val found = Test.findFromKey(instance.key)
    println("${found!!.key}")
}

sealed class Test(val key: String) {
    object First : Test("First")
    object Second : Test("Second")
    
    companion object {
        val firstAndSecond = listOf(Test.First, Test.Second)
        
        fun findFromKey(key: String): Test? = firstAndSecond.firstOrNull { it.key == key }
    }
}

the one that works is this:

https://pl.kotl.in/KrPlX9Kgp

fun main() {
    
    val instance = Test.First
    val found = Test.findFromKey(instance.key)
    println("${found!!.key}")
}

sealed class Test(val key: String) {
    object First : Test("First")
    object Second : Test("Second")
    
    companion object {
        fun findFromKey(key: String): Test? = firstAndSecond.firstOrNull { it.key == key }
    }
}

  val firstAndSecond = listOf(Test.First, Test.Second)

So what's happening here? I thought companion objects and its contents are statically initialized with the class, like in Java when you declare something static. Also when I add @JvmStatic annotation like this, it also works(this works when I do it in Android Studio, but not on the online Kotlin playground, probably because of compiler plugins):

https://pl.kotl.in/TknCpH2kY

fun main() {
    
    val instance = Test.First
    val found = Test.findFromKey(instance.key)
    println("${found!!.key}")
}

sealed class Test(val key: String) {
    object First : Test("First")
    object Second : Test("Second")
    
    companion object {
        @JvmStatic
        val firstAndSecond = listOf(Test.First, Test.Second)
        
        fun findFromKey(key: String): Test? = firstAndSecond.firstOrNull { it.key == key }
    }
}

Here is the decompiled crashing code:

https://pastebin.com/0pNgn0Ef

Here is the decompiled working code:

https://pastebin.com/a1KWAWZE

So any explanations are welcome? Thanks!

0 Answers
Related