Android Room类型转换多个枚举类型

JGu*_*Guo 7 enums kotlin android-room

我正在为我的Room数据库编写一个类型转换器.我有几个自定义枚举类,我想将它们存储在数据库中时将它们全部转换为它的序数.因此,有没有任何方法可以简化它(例如传递通用枚举类型),而不是为每个类编写以下内容?

class Converter {

    @TypeConverter
    fun toOrdinal(type: TypeA): Int = type.ordinal

    @TypeConverter
    fun toTypeA(ordinal: Int): TypeA = TypeA.values().first { it.ordinal == ordinal }

    @TypeConverter
    fun toOrdinal(type: TypeB): Int = type.ordinal

    @TypeConverter
    fun toTypeB(ordinal: Int): TypeB = TypeB.values().first { it.ordinal == ordinal }

    ...
}
Run Code Online (Sandbox Code Playgroud)

zsm*_*b13 10

正如所讨论的这里,房间不能在目前处理的通用转换器.我认为您可以做的最好的事情就是创建扩展,以便更快地编写这些枚举转换器:

@Suppress("NOTHING_TO_INLINE")
private inline fun <T : Enum<T>> T.toInt(): Int = this.ordinal

private inline fun <reified T : Enum<T>> Int.toEnum(): T = enumValues<T>()[this]
Run Code Online (Sandbox Code Playgroud)

这会简化每对转换器到这段代码:

@TypeConverter fun myEnumToTnt(value: MyEnum) = value.toInt()
@TypeConverter fun intToMyEnum(value: Int) = value.toEnum<MyEnum>()
Run Code Online (Sandbox Code Playgroud)

或者,如果您可能存储空值:

@TypeConverter fun myEnumToTnt(value: MyEnum?) = value?.toInt()
@TypeConverter fun intToMyEnum(value: Int?) = value?.toEnum<MyEnum>()
Run Code Online (Sandbox Code Playgroud)