如何在Kotlin中从字符串创建枚举? [英] How do I create an enum from a string in Kotlin?

查看:749
本文介绍了如何在Kotlin中从字符串创建枚举?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个带有某些实例FooBar的枚举.如果我有字符串"Foo",如何从中实例化Foo枚举?在C#中将为Enum.Parse(...),在Kotlin中是否具有等效项?

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? In C# it would be Enum.Parse(...), is there an equivalent in Kotlin?

目前,我发现的最好的方法是创建一个工厂,该工厂可以打开所有可能的字符串,但这容易出错,并且对于较大的枚举而言效果不佳.

Currently, the best I have found is to create a factory that switches on all possible strings, but that is error prone and performs poorly for large enumerations.

推荐答案

Kotlin枚举类具有静态"功能valueOf以按字符串获取枚举条目(例如Java枚举).另外,它们具有静态"功能values以获取所有枚举条目.示例:

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

这篇关于如何在Kotlin中从字符串创建枚举?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆