— Kotlin, Enum, Programming — 1 min read
Have you ever encountered the error message "‘name’ in ‘enum’ is final and cannot be overridden" while working with enums in Kotlin? This issue often arises when attempting to override the name
property in an enum class, and it can be frustrating to deal with. However, fear not! In this article, we'll delve into what causes this error and explore effective solutions to overcome it. By the end, you'll have a clear understanding of how to work around this limitation in Kotlin.
When we attempt to override the name
property in an enum class in Kotlin, we are met with the error message "‘name’ in ‘enum’ is final and cannot be overridden." This occurs because the name
property in an enum class is treated as a final property, meaning that it can't be modified or overridden by default.
Let's consider a scenario where we have an enum class representing different types of fruits:
1enum class Fruit {2 APPLE, BANANA, ORANGE;3
4 var displayName: String = ""5 get() {6 return field7 }8 set(value) {9 field = value10 }11
12 override fun toString(): String {13 return if (displayName.isNotEmpty()) displayName else super.name14 }15}
In this example, we've defined a displayName
property within the enum class Fruit
to provide a custom name for each fruit type. Here, we attempt to override the toString()
method to return the custom display name if it's set, falling back to the default enum name otherwise.
One way to address the inability to override the name
property directly is to use a when
expression to map the enum values to custom names. Let's modify our previous example to achieve this:
1enum class Fruit {2 APPLE, BANANA, ORANGE;3
4 var displayName: String = ""5 get() {6 return field7 }8 set(value) {9 field = value10 }11
12 fun getCustomName(): String {13 return when (this) {14 APPLE -> "Apple"15 BANANA -> "Banana"16 ORANGE -> "Orange"17 }18 }19}
By utilizing a when
expression within the getCustomName()
function, we're able to return custom names based on the enum values without directly overriding the name
property.
Another approach involves storing custom names as properties within the enum constants themselves. Let's modify our enum example once more to demonstrate this technique:
1enum class Fruit(val displayName: String) {2 APPLE("Apple"), BANANA("Banana"), ORANGE("Orange");3
4 override fun toString(): String {5 return displayName6 }7}
In this updated example, we've added a displayName
property to each enum constant in the Fruit
enum. By doing so, we can simply override the toString()
method to return the custom name associated with each enum value.
In your future Kotlin projects, keep these solutions in mind to effortlessly manage and customize enum representations based on your specific requirements!