Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Initializing map in companion object throws ExceptionInInitializerError

Tags:

kotlin

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.

like image 682
Some Noob Student Avatar asked Mar 19 '26 17:03

Some Noob Student


1 Answers

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

like image 96
Sergei Rybalkin Avatar answered Mar 22 '26 11:03

Sergei Rybalkin