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

Can I access enum property with string in kotlin?

I have an enum of regions like this:

enum class Regions(val location:String){
   REGION_1("London"),
}

Is there a way to access the properties of region_1 with just a string like in the below function?

fun access(name:String){
    return Regions.<modifed_name>.location 
}

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 :

You can convert your string to enum using valueOf(value: string) and then use the location

fun access(name:String): String = Regions.valueOf(name.uppercase()).location 

Like @lukas.j

App will crash if the name is not in the enum list.

To prevent crash you can return a nullable string? instead of a string with the following code :

fun access(name:String): String? = Regions.values().firstOrNull() { it.name == name }?.location

And like @lukasJ said in his answer, you can return a default value if the name cannot be found

fun access(name:String): String = Regions.values().firstOrNull() { it.name == name }?.location ?: "myDefaultValue"
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