So I have two examples for you.
The one that crashes with a NPE is this:
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:
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):
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:
Here is the decompiled working code:
So any explanations are welcome? Thanks!