Kotlin中UInt中的位标志EnumSet



我的Kotlin应用程序中有很多enum class。它们都表示我需要在EnumSet<>UInt之间转换的位标志,以便与FPGA板进行串行通信。

如何提供一些适用于所有枚举的扩展方法?

枚举不允许类继承。EnumSet无法引用接口。我不知道还能尝试什么。

谢谢!

enum class ReadFlag(val bits: UInt) {
DATA_READY(1u)
BUSY(2u)
}
typealias ReadFlags = EnumSet<ReadFlag>
enum class WriteFlag(val bits: UInt) {
UART_RESET(1u)
BUSY(2u)
PAGE_DATA(4u)
}
typealias WriteFlags = EnumSet<WriteFlag>
fun ReadFlags.asUInt(): UInt =
this.fold(0u) { acc, next -> acc or next.bits }
fun WriteFlags.asUInt(): UInt =
this.fold(0u) { acc, next -> acc or next.bits }

这导致了这个错误:

error: platform declaration clash: The following declarations have the same JVM signature (asUInt(Ljava/util/EnumSet;)I):

为常见成员编写一个接口:

interface Flags {
val bits: UInt
}

实现接口:

enum class ReadFlag(override val bits: UInt): Flags {
DATA_READY(1u),
BUSY(2u)
}
enum class WriteFlag(override val bits: UInt): Flags {
UART_RESET(1u),
BUSY(2u),
PAGE_DATA(4u)
}

然后您可以使您的asUInt通用:

fun <E> EnumSet<E>.asUInt(): UInt where E : Enum<E>, E: Flags =
this.fold(0u) { acc, next -> acc or next.bits }

最新更新