Enum method not available in enum constructor

Is there any reason why the first option is not valid in Koltin? What am I missing?
The name method is available in the constructor (otherwise MyEnum3 should be illegal as well), and property declaration with default value is valid (otherwise MyEnum2 should be illegal). So why is MyEnum illegal?

Thank you

// This is not OK for the compiler
enum class MyEnum(val uiName: String = this.name) {
    TEST,
    TEST_WITH_NAME("NAME");
}

// This is OK for the compiler
enum class MyEnum2(val uiName: String = "this.name") {
    TEST,
    TEST_WITH_NAME("NAME");
}

// This is OK for the compiler
enum class MyEnum3(uiName: String? = null) {
    TEST,
    TEST_WITH_NAME("NAME");
    
    val uiName = uiName ?: this.name
}
2 Likes

#1 doesn’t work
While constructing an object you never have access to the object being constructed.

#2 works
since you’re simply having a default value for a constructor parameter.

#3 works
because name is a property of the base class Enum which is initalized before the members of MyEnum3.

In general a class definition is “read in order” so while initializing memebers you can reference other members which appear before/above the one you’re initializing. If there’s subclassing you can use the base class’ members as those are always initialized before the derived class.

1 Like

This is not entirely correct. You always have access when constructor is already began executing, otherwise how would you construct it?

In this case, it’s not valid because you never have access to the object before it even began being constructed!

The general execution order is:

  1. Space is allocated, and all fields are initialized to default values.
  2. The actual constructor parameters are evaluated.
  3. The constructors are called in order from Object down the class hierarchy.

In this case:

  1. Space is allocated, and all fields are initialized to their default values (the field backing the name property is of course initialized to null).
  2. The actual constructor parameters are evaluated.
  3. The Object constructor is called.
  4. The Enum constructor is called, setting the name property to its valid value.
  5. The MyEnum constructor is called.

If this.name would be allowed, it would evaluate to null during step 2 because it is only initialized to a non-null value later at step 3. To avoid such confusing behavior, it is prohibited.

3 Likes