Can Enum properties be marked as compile time constants somehow?


#1

Sometimes I need to pass a string to an annotation, and I want to use for that the name of an Enum instance, or something directly derived from an Enum name, or a val constructor param to an Enum. Something that would effectively be a compile time constant therefore, like an Enum instance is considered a compile time constant.

However the compiler doesn’t consider it a compile time constant so I’m wondering if it’s possible to mark some read-only properties in an Enum as such with the const keyword:

enum class MyEnum {
    E1, E2;

    const val roleName : String
    get() = "ROLE_" + name
}

class Foo {

    @RolesAllowed(MyEnum.E1.roleName)
    fun bar() {}
}

Could this be considered for a future enhancement to Kotlin?


#2

A property with a custom getter can never be a compile-time constant. Kotlin does not support evaluating code at compile time.


#3

What about making a special case for that on:

  1. Enum name property (which is a compile time constant String)

  2. Inline read-only properties that can be evaluated to compile time constants:

    enum class MyEnum {
    E1, E2;

     val roleName : String
     inline get() = "ROLE_" + name
    

    }

Since String concatenations can be evaluated at compile time.

For me this would have advantages since I can guarantee at compile time that annotations like @RolesAllowed have application-defined valid values.


#4

#5

Oops, now I get 100 points minus! :smiley:

Discussion closed in other words.

Thanks anyway for answering and explaining.