How to force immediate instantiation of enum values?

Viewed 355

How to force immediate instantiation of enum values?

By default, in Kotlin enums are instantiated on first access (like objects/singletons), i.e., the following minimal example

class Foo

fun create(msg: String) = Foo().also { println("$msg") }

enum class A(val foo: Foo) {
    ONE(create("1")),
    TWO(create("2"))
}

enum class B(val foo: Foo) {
    THREE(create("3")),
    FOUR(create("4"))
}

fun main() {
    println("main")
    println(A.ONE)
}

outputs:

main
1
2
ONE

Is it possible to force the enums to be instantiated directly/statically before main, such that the output is as follows?

1
2
3
4
main
ONE

Sure, I could just put something like val ignore = listOf(A.ONE, B.THREE) somewhere, but I'd like to avoid such manual repetition.

Maybe there's a way using some existing annotation, or creating a new one, or something else? :)

1 Answers

JVM loads classes only on first access. This is not only for kotlin but also for Java. For Java we have ways to initialize a class before main, for instance, static initializer block, or Class.forName. Similarly you can use the static initializer block in Kotlin.

object Temp {
    init {
        A.ONE
    }

    @JvmStatic fun main(args: Array<String>) {
        println("main")
        println(A.ONE)
    }
}
Related