How do I create an enum from a string in Kotlin?

Kotlin enum classes have "static" function valueOf to get enum entry by string(like Java enums). Additionally they have "static" function values to get all enum entries. Example:

enum class MyEnum {
  Foo, Bar, Baz
}

fun main(args : Array<String>) {
  println(MyEnum.valueOf("Foo") == MyEnum.Foo)
  println(MyEnum.valueOf("Bar") == MyEnum.Bar)
  println(MyEnum.values().toList())
}

Would do it like

enum class MyEnum {
  Foo, Bar, Baz
}

val value = MyEnum.values().firstOrNull {it.name == "Foo"} // results to MyEnum.Foo

As bashor suggested, use MyEnum.valueOf() but please have in mind that it throws an exception if value can't be found. I recommend using:

enum class MyEnum {
  Foo, Bar, Baz
}

try {
   myVar = MyEnum.valueOf("Qux")
} catch(e: IllegalArgumentException) {
   Log.d(TAG, "INVALID MyEnum value: 'Qux' | $e")
}

Tags:

Kotlin