0

我正在尝试将Room TypeConverter(Room 版本 2.2.5)用于枚举,但是在编译时我收到了Class is referenced as a converter but it does not have any converter methods.正在查看 Converter.java 类,它确实缺少我定义的转换器方法。我已将 Gradle 中的 annotationProcessorOptions 设置为"room.incremental":"true". 有没有人遇到过这个问题?

enum class Exposure(val label: String) {
    SUN("Sun"),
    PARTIAL_SUN("Partial sun"),
    SHADE_PARTIAL_SUN("Shade, Partial sun"),
    SHADE("Shade"),
    SHADE_SUN("Shade, Sun");

    companion object {
        fun labels(): List<String> {
            return values().map { it.label }.toList()
        }
    }
}
class Converters {
    @TypeConverter
    fun toExposure(value: String): Exposure {
        return value.let { Exposure.valueOf(it) }
    }

    @TypeConverter
    fun fromExposure(exposure: Exposure): String {
        return exposure.name
    }
}
@Entity(tableName = "plant")
data class PlantEntity(
    var name: String,
    var exposure: Exposure
) {
    @PrimaryKey(autoGenerate = true)
    var id: Int = 0
}
@Database(entities = [PlantEntity::class], version = 1, export = false)
@TypeConverters(Converters::class)
abstract class PlantDatabase : RoomDatabase() {

    abstract fun plantDao(): PlantDao

    ...
}
4

1 回答 1

0

您可以尝试使用对象并使用@JvmField

object Converters {
    @TypeConverter
    @JvmStatic
    fun toExposure(value: String): Exposure =
        value.let { Exposure.valueOf(it) }


    @TypeConverter
    @JvmStatic
    fun fromExposure(exposure: Exposure): String =
        exposure.name
}
于 2020-10-11T22:06:58.743 回答