如何在 Kotlin 为 enum 创建“ static”方法?

Kotlin 已经有很多枚举类的“静态”方法,比如 valuesvalueOf

例如,我有枚举

public enum class CircleType {
FIRST
SECOND
THIRD
}

我如何才能添加静态方法,如 random(): CircleType? 扩展函数似乎不适合这种情况。

53713 次浏览

Just like with any other class, you can define a class object in an enum class:

enum class CircleType {
FIRST,
SECOND,
THIRD;
companion object {
fun random(): CircleType = FIRST // http://dilbert.com/strip/2001-10-25
}
}

Then you'll be able to call this function as CircleType.random().

EDIT: Note the commas between the enum constant entries, and the closing semicolon before the companion object. Both are now mandatory.