Android Room类型转换多种枚举类型 [英] Android Room type convert multiple enum types

查看:1037
本文介绍了Android Room类型转换多种枚举类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在为我的Room数据库编写一个类型转换器.我有几个自定义枚举类,当我将其存储在数据库中时,我想将它们全部转换为其普通形式.因此,除了为每个单个类编写以下代码之外,还有什么方法可以简化它(例如,传递通用枚举类型)?

I am writing a type converter for my Room database. I have a couple custom enum classes and I want to convert all of them to its ordinals when stored in the database. So, instead of writing the following for every single class, is there any way to simplify it (such as pass in a generic enum type)?

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 }

    ...
}

推荐答案

此处所述,房间无法处理目前,通用转换器.我认为您能做的最好的事情就是创建扩展程序,以使编写这些枚举转换器的速度更快:

As discussed here, Room can't handle generic converters at the moment. I think the best you can do is create extensions that make writing these enum converters quicker:

@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]

这会将每对转换器简化为以下代码:

This would simplify each pair of converters to this code:

@TypeConverter fun myEnumToTnt(value: MyEnum) = value.toInt()
@TypeConverter fun intToMyEnum(value: Int) = value.toEnum<MyEnum>()

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

Or if you might be storing null values:

@TypeConverter fun myEnumToTnt(value: MyEnum?) = value?.toInt()
@TypeConverter fun intToMyEnum(value: Int?) = value?.toEnum<MyEnum>()

这篇关于Android Room类型转换多种枚举类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆