enums - 向 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 标志值定义为常量。也许是一个伴生对象,但我认为我不能扩展现有的枚举并添加一个伴生对象。
有任何想法吗?
解决方案
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
...
}
}
推荐阅读
- typo3 - TYPO3 以非管理员身份删除 FileReference
- nvidia - What does "DSO" stand for as in, "kernel version 460.39.0 does not match DSO version 460.56.0"?
- mathematical-optimization - SAT ‒ 将最大变量数设置为 true
- tcl - 有什么方法可以为 tk_messagebox 提供来自 TCL 本身的输入,而不是通过用户单击按钮?
- c# - DotNet HttpClient.DefaultProxy 属性未读取 Win10 上的系统设置
- python - 如何合并多个键并根据条件添加重命名信息?
- java - 使用没有密码的全局密钥库 - java HttpClient
- php - 如何解决作曲家更新错误
- python - 在 windows 10 (python 版本 3.9) 中安装 python 喊模块
- c++ - ZeroMQ:链接到消息关系