Enum lazy properties

I am wondering how enum properties are handled by kotlin. If we have an enumeration with the following structure:

enum class MyEnun(var sampleObject: MyObjectType){
   ONE(MyObjectType(blabla)),
   TWO(MyObjectType(blabla))
}

Are two instances of MyObjectType created in a lazy way, or, conversely, will they be created when the enumeration is created?

+4
source share
1 answer

All instances are created simultaneously.

enum class Foo(input: String) {

    ONE("one"),
    TWO("two");

    init {
        println("Received $input")
    }
}

fun main(args: Array<String>) {
    Foo.ONE
}

When I ran this, I got the following:

Received one
Received two

If they were created lazily, I would expect that I would only print “Received one”.

+5
source

Source: https://habr.com/ru/post/1691933/


All Articles