首页 > 解决方案 > 向 Kotlin 中的现有枚举添加属性

问题描述

给定在外部 api 中定义的以下枚举。

public enum Status {
  COMPLETE,
  RUNNING,
  WAITING
}

我想要一种为每个枚举值添加一个 int 标志的方法。我知道我可以扩展枚举:

fun Status.flag(): Int {
    when(this) {
        RUNNING -> return 1;
        WAITING -> return 2;
        else -> return 0;
    }
}

但是我想将这些 int 标志值定义为常量。也许是一个伴生对象,但我认为我不能扩展现有的枚举并添加一个伴生对象。

有任何想法吗?

标签: enumskotlin

解决方案


enum您可以将扩展属性/方法添加到/ class/etc的伴随对象中。如果存在:

val Status.Companion.COMPLETE_INT = 0
val Status.Companion.RUNNING_INT = 1

但实际上,如果没有,您目前无法“创建”伴随对象。因此,只需将常量放入您自己的非伴随对象中:

object StatusFlags {
    const val COMPLETE_INT = 0
    const val RUNNING_INT = 1
    const val WAITING_INT = 2
}

fun Status.flag(): Int {
    when(this) {
        RUNNING -> return StatusFlags.RUNNING_INT
        ...
    }
}

推荐阅读