4

I'm wondering how the enum properties are treated by kotlin. If we have an enum with the following structure:

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

Are the two MyObjectType instances created in a lazy way or, on the contrary, they will be created when the enum is created?

rdiaz82
  • 996
  • 12
  • 31
  • This might as well be a duplicate of [this](https://stackoverflow.com/questions/19971982/enum-class-initialization-in-java) – Salem Jan 09 '18 at 15:33

1 Answers1

5

All of the instances are created at the same time.

enum class Foo(input: String) {

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

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

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

When I ran that, I got the following:

Received one
Received two

If they were created lazily, I would expect only "Received one" to have printed.

Todd
  • 30,472
  • 11
  • 81
  • 89