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

前端 未结 4 1519
情书的邮戳
情书的邮戳 2021-01-03 19:42

I have an enum with some instances Foo and Bar. If I have a string \"Foo\", how can I instantiate a Foo enum from that?

4条回答
  •  执念已碎
    2021-01-03 20:04

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

提交回复
热议问题