给定在外部api中定义的以下枚举。
public enum Status {
COMPLETE,
RUNNING,
WAITING
}我想要一种方法来添加一个int标志到每个枚举值。我知道我可以扩展枚举:
fun Status.flag(): Int {
when(this) {
RUNNING -> return 1;
WAITING -> return 2;
else -> return 0;
}
}但是,我希望将这些int标志值定义为常量。可能是一个伴生对象,但我不认为我可以扩展现有的枚举并添加一个伴生对象。
有什么想法吗?
发布于 2018-10-04 23:26:35
除非您使用的字段已存在于原始枚举中(如序数),否则如果不将外部枚举包装在您自己的枚举中,您将无法执行所要求的操作。
当然,您可以使用序数,但是较新版本的外部API可能会更改枚举中项的顺序,因此我不推荐使用它。但是,如果你真的想这样做,你可以这样做(同样,不推荐这样做):
val Status.flag: Int
get() = this.ordinal但我绝对建议你把它包装起来。这样,您就可以保证您定义的标志整数不会改变。
enum class MyStatus(val status: Status, val flag: Int) {
COMPLETE(Status.COMPLETE, 0),
RUNNING(Status.RUNNING, 1),
WAITING(Status.WAITING, 2);
companion object {
private val STATUS_TO_MYSTATUS = values().associateBy { it.status }
fun fromStatus(status: Status): MyStatus {
return STATUS_TO_MYSTATUS[status] ?: throw Exception("No MyStatus found for status ${status.name}")
}
}
}然后,您可以使用MyStatus.fromStatus(...)将状态转换为MyStatus。或者你可以在Status中添加一个扩展功能,以便轻松转换为MyStatus。
fun Status.toMyStatus() = MyStatus.fromStatus(this)发布于 2018-10-05 05:33:33
您可以将扩展属性/方法添加到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
...
}
}https://stackoverflow.com/questions/52649501
复制相似问题