在Kotlin中具有相同值的两个枚举常量

huangapple go评论60阅读模式
英文:

Two enum constants in Kotlin with the same value

问题

在Kotlin中是否可以为枚举常量创建一个'alias'(别名),以便可以通过两个名称引用同一个枚举常量?

例如:如果MyEnum是一个包含两个常量A1A2的枚举的名称,那么MyEnum.B1应该与MyEnum.A1实际上是相同的,MyEnum.B2应该与MyEnum.A2实际上是相同的。

英文:

Is it possible to create an 'alias' for an enum constant in Kotlin, so that its possible to refer to one single enum constant by two names?

Eg: If MyEnum is the name of the enum with 2 constants A1 and A2, then MyEnum.B1 should effectively be the same as MyEnum.A1 and MyEnum.B2 should effectively be the same as MyEnum.A2.

答案1

得分: 1

你可以通过在枚举内部将 'alias' 名称作为静态 val 包含来简单实现此操作。

enum class MyEnum {
    A1, A2;

    companion object {
        val B1 = A1
        val B2 = A2
    }
}
英文:

You can do this simply by including the 'alias' names as static vals inside the enum.

enum class MyEnum {
    A1, A2;

    companion object {
        val B1 = A1
        val B2 = A2
    }
}

huangapple
  • 本文由 发表于 2023年6月19日 01:35:09
  • 转载请务必保留本文链接:https://go.coder-hub.com/76501798.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定