[英]EnumSet of bit flags into UInt in Kotlin
I have a lot of enum class
in my Kotlin application.我的 Kotlin 应用程序中有很多
enum class
。 They all represent bit flags that I need to convert between EnumSet<>
and UInt
for serial communication with an FPGA board.它们都代表位标志,我需要在
EnumSet<>
和UInt
之间进行转换,以便与 FPGA 板进行串行通信。
How can I provide some extension methods that apply to all those Enums?我怎样才能提供一些适用于所有这些枚举的扩展方法?
Enums don't allow class inheritance. EnumSet can't reference an interface.枚举不允许 class inheritance。EnumSet 不能引用接口。 I'm not sure what else to try.
我不确定还能尝试什么。
Thanks!谢谢!
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 }
This results in this error:这会导致此错误:
error: platform declaration clash: The following declarations have the same JVM signature (asUInt(Ljava/util/EnumSet;)I):
Write an interface for the common members:为普通成员写一个接口:
interface Flags {
val bits: UInt
}
Implement the interface:实现接口:
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)
}
Then you can make your asUInt
generic:然后你可以使你的
asUInt
通用:
fun <E> EnumSet<E>.asUInt(): UInt where E : Enum<E>, E: Flags =
this.fold(0u) { acc, next -> acc or next.bits }
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.