Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Kotlin Enum that is simultaneously a String

I’d like to define a set of constants strings as a convenient enumeration for peace of mind on compile time. It feels obvious (with my Python background at least) that simple enumerations could be used as string instances.

// Fine for overall use
enum class Things{ FIRST, SECOND, THIRD }
containsThings[Things.FIRST]

// If a String is expected, this works but has extra stuff
enum class Things(val v: String){
    FIRST("FIRST"), SECOND("SECOND"), THIRD("THIRD")
}
// I want to get rid of ".v"
containsThings[Things.FIRST.v]

// Naïve desired syntax
enum class Things: String { FIRST, SECOND, THIRD }
containsThings[Things.FIRST]

Am I missing something obvious?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

For that to work, your enum class would have to be a subclass of String. That’s doubly impossible, first because you can’t specify a superclass for an enum class, and second because String is not open and cannot be subclassed.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading