user12115080
user12115080

Reputation:

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 
}

Upvotes: 1

Views: 1852

Answers (2)

Jolan DAUMAS
Jolan DAUMAS

Reputation: 1374

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 

Upvotes: 3

lukas.j
lukas.j

Reputation: 7163

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

Upvotes: 2

Related Questions