1

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 
}

2 Answers 2

3

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 
Sign up to request clarification or add additional context in comments.

2 Comments

Note that this will crash the application if name is not REGION_1, REGION_2, etc.
@lukas.j It will throw an exception (specifically, an IllegalArgumentException). Whether that causes a crash depends on whether it's caught anywhere, which thread it's running in, and the type of program.
2
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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.