Consider the following class:
sealed class Fruit(val id: String, val label: String) {
object orange : Fruit("Citrus sinensis", "orange")
object watermelon : Fruit("Citrullus lanatus", "watermelon")
companion object {
val values = listOf(orange, watermelon)
val valuesByID = values.associateBy { it.id } // <<< error here
}
}
This class compiles fine, but when it is referenced at runtime (eg: val oj = Fruit.orange) an error will be thrown.
java.lang.ExceptionInInitializerError
at com.example.sandbox.App.<clinit>(App.kt:13)
at java.lang.reflect.Constructor.newInstance(Native Method)
at java.lang.Class.newInstance(Class.java:1606)
However, if the valuesByID line is removed, then the error will not be thrown. Why is this happening?
The runtime environment is Android, if that matters.
It is a known issue https://youtrack.jetbrains.com/issue/KT-25738 reported in July 2018.
General problem is using object which is subclass of a sealed class in its companion
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With