在 Kotlin 中的枚举类的方法中访问枚举值

Vit*_*lii 0 enums kotlin

我有枚举类,里面声明了方法

enum class MyEnum {
    VAL1, VAL2, VAL3;

    fun myFunc(): Any{
         // Here I want to access selected value
         // VAL1 in my example
    }
}
Run Code Online (Sandbox Code Playgroud)

我可以这样调用这个方法

MyEnum.VAL1.myFunc()
Run Code Online (Sandbox Code Playgroud)

但是是否有可能在内部myFunc调用 value 方法?在我的例子中它是VAL1.

小智 5

您可以使用thisand this.ordinalwhich 返回此枚举常量的序号
如果您这样做:

fun myFunc(): Any{
    val array = MyEnum.values()
    println(array[this.ordinal])
    println(this)
    return array[this.ordinal]
}
Run Code Online (Sandbox Code Playgroud)

然后打电话MyEnum.VAL2.myFunc()你会看到VAL2