Is 'name' not allowed in enums?

Hi,

I have an enum class which has an enum value called name


enum class ColumnNames {
    id,
    name,
}

fun main() {
    println(ColumnNames.name)
}

and it fails to compile with

Conflicting declarations: enum entry name, public final val name: String

Is there a way to have an enum value called “name”? I tried putting it between backticks, but it didn’t work.

Here’s this example in playground:
https://play.kotlinlang.org/#eyJ2ZXJzaW9uIjoiMS42LjEwIiwicGxhdGZvcm0iOiJqYXZhIiwiYXJncyI6IiIsIm5vbmVNYXJrZXJzIjp0cnVlLCJ0aGVtZSI6ImlkZWEiLCJjb2RlIjoiXG5lbnVtIGNsYXNzIENvbHVtbk5hbWVzIHtcbiAgICBpZCxcbiAgICBuYW1lLFxufVxuXG5mdW4gbWFpbigpIHtcbiAgICBwcmludGxuKENvbHVtbk5hbWVzLm5hbWUpXG59In0=

That’s not possible. Note that convetions suggest either Name or NAME.

@al3c thanks for the quick answer! Yes, I know that it should be NAME, however this is from a generated code (a client generated from a graphql schema) and it uses the names found in the schema.

Can you point me to where is this defined that “name” cannot be an enum member?

It’s not specifically forbidden, but all enums inherit from java.lang.Enum
https://docs.oracle.com/javase/7/docs/api/java/lang/Enum.html

and that has already a name property.

1 Like

Yes, of course, I didn’t think of Java Enum, it makes sense! Thanks again!

Please vote for https://youtrack.jetbrains.com/issue/KT-44885

1 Like

Thanks, I just did!

That is both true and false. The name property is inspired from Java, but it’s not about inheritance. You also can’t use name in Kotlin/JS, where nothing inherits from Java.

It actually is about inheritance, but of kotlin.Enum, see language specification:

kotlin.Enum<T> is the built-in parameterized classifier type which is used as a superclass for all enum classes: every enum class E is implicitly a subtype of kotlin.Enum<E> .

On JVM they happen to be the same:

fun main() {
    println(java.lang.Enum::class == kotlin.Enum::class)
}
1 Like