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
}
CodePudding user response:
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
CodePudding user response:
enum class Regions(val location: String) {
REGION_1("London"),
REGION_2("Berlin"),
REGION_3("Pairs")
}
fun access(name:String): String {
return Regions.values().firstOrNull() { it.name == name }?.location ?: "location not found"
}
println(access("REGION")) // Output: location not found
println(access("REGION_2")) // Output: Berlin