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
}
>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"