Conflicting 'name' declaration in enum

2020-03-30 04:14发布

问题:

I have a simple enum class in which I would like to have a field called name.

enum class DeviceFieldQuery(val clazz: Class<*>) {
    id(Int::class.java),
    name(String::class.java),
}

Unfortunately, this does not seem to work in Kotlin. Compilation fails with the message:

Error:(9, 5) Kotlin: Conflicting declarations: enum entry name, public final val name: String

The same Enum class as Java code works fine. How may I solve this in Kotlin?

回答1:

Enums in Kotlin already have a name property already defined (like Java). This is conflicting with your enum called name. To fix it, you could capitalize it, which is more idiomatic:

enum class DeviceFieldQuery(val clazz: Class<*>) {
    Id(Int::class.java),
    Name(String::class.java),
}


标签: enums kotlin