3

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?

petarov
  • 131
  • 2
  • 12

1 Answers1

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),
}
Todd
  • 30,472
  • 11
  • 81
  • 89
  • Thank you, but I do not want to use capitalization at this point. It is a requirement that the fields are declared lowercase. – petarov Sep 28 '18 at 14:44
  • You can't call it `name` because it conflicts with a property on the enum already, you have to change it to something else, whether that is capitalized or just spelled differently. – Todd Sep 28 '18 at 14:45
  • As I mentioned already, I have to have it as `name`. If that's not possible then I should just consider this a limitation of the language at this point. :( – petarov Sep 28 '18 at 14:49
  • That's what I'm telling you, yes. It's also more idiomatic to have capitalized enums. Good luck on your project. – Todd Sep 28 '18 at 14:54
  • 1
    Idiomatic if not enforced by the compiler is just another rule that can and will be broken. In any case, there are many java enums out there with this entry. Kind of unfortunate for kotlin to claim such a common one as somehow special. I ran into two trying to migrate some code today. Out of curiosity, why is name a separate entry under the enum instead of a property of the value, like it is on the Java side? – Jilles van Gurp Nov 28 '18 at 11:28