Elye
Elye

Reputation: 60081

Is it possible to override the name of ENUM for Kotlin?

I have my enum as below

    enum class ImagesType(val descriptor: String) {
        BIGGER("Bigger Image - Fall"),
        SMALLER("Smaller Image - Lion"),
        TALLER("Taller Image - Tree"),
        LONGER("longer Image - Bridge")
    }

This is because the name is the same as the enum characters. I am hoping to override the name with the description, where the following will be true instead

I tried

    enum class ImagesType(override val name: String) {
        BIGGER("Bigger Image - Fall"),
        SMALLER("Smaller Image - Lion"),
        TALLER("Taller Image - Tree"),
        LONGER("longer Image - Bridge")
    }

But it fails stating that name is final.

Upvotes: 4

Views: 7565

Answers (1)

Elye
Elye

Reputation: 60081

I use way to get what I wanted.

    enum class ImagesType(val descriptor: String) {
        BIGGER("Bigger Image - Fall"),
        SMALLER("Smaller Image - Lion"),
        TALLER("Taller Image - Tree"),
        LONGER("longer Image - Bridge");

        override fun toString(): String {
            return descriptor
        }

        companion object {
            fun getEnum(value: String): ImagesType {
                return values().first { it.descriptor == value }
            }
        }
    }

So it get the result I need

  • When I println(ImagesType.BIGGER) it will print Bigger Image - Fall
  • When I val x = ImagesType.getEnum("Smaller Image - Lion"), it will get val x = SMALLER

I kind of workaround of overriding valueOf by replacing it with getEnum. Looks like valueOf can't be overriden.

Upvotes: 8

Related Questions