Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

enums

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")
    }
  • When I println(ImagesType.BIGGER) it will print BIGGER
  • When I val x = ImagesType.valueOf("SMALLER"), it will get val x = SMALLER

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

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

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.

like image 936
Elye Avatar asked Oct 19 '25 22:10

Elye


1 Answers

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.

like image 199
Elye Avatar answered Oct 21 '25 11:10

Elye



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!