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: