Enum companion object load order

When enum class companion object is actually loaded?

Can’t understand why following code gives NPE.

enum class TestEnum(val callback: () -> Unit) {
    EV(::testFunc);
    companion object {
        @JvmStatic // JvmStatic doesn't change anything
        fun testFunc() {
            println("Hello, NPE")
        }
    }
}

fun main() {
    val fail = TestEnum.EV.callback()
    println("Hello, NPE!!!")
}

As stated in docs companion object initialized when class is loaded.

  • A companion object is initialized when the corresponding class is loaded (resolved) that matches the semantics of a Java static initializer.

Playground:

The enum values EV here is loaded before the companion object is.

So enum values can’t refer to anything in the companion object. However companion object memebers can refer to the enum values.

3 Likes

https://youtrack.jetbrains.com/issue/KT-37165

1 Like