我相信这很可能是一个错误。
如果您有 UInt8,那么 Room 会生成 AppDatabase_Impl,其中的表将 UByte 识别为 INTEGER,例如
_db.execSQL("CREATE TABLE IF NOT EXISTS `UInt8` (`key` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `name` TEXT NOT NULL, `testvalue` INTEGER NOT NULL, `size` INTEGER NOT NULL, `readOnly` INTEGER NOT NULL)");
- 根据
createAllTables
method
- 注意值已更改为测试值以确保它正在重新生成。
因此 Room 知道 UByte 等同于 INTEGER 列类型。
我认为,问题在于它处理需要 Int,因此默认的 getter 和 setter 是不够的。此外,TypeConverters 被忽略,因为 Room 显然知道如何处理。
如果您改为使用:-
@Entity
data class UInt8(
@PrimaryKey(autoGenerate = true)
var key: Int,
var name: String = "uint8-test",
var testvalue: Int = 0,
var size: Int = 1,
var readOnly: Boolean = true
) {
constructor(key: Int, name: String, testvalue: UByte, size: Int, readOnly: Boolean): this(key,name, testvalue.toInt(),size,readOnly)
}
然后 Room 不会抱怨,但检索它时 testvalue 将是一个 Int 。但是,您需要重写 getter 以从 Int 返回 Ubyte。
- see 覆盖 Kotlin 数据类的 getter https://stackoverflow.com/questions/38492103/override-getter-for-kotlin-data-class/46376746#46376746
但是,如果您创建一个类来屏蔽 Room 如何处理 UByte,并实现合适的类型转换器,那么它们就会发挥作用。
所以如果你有例如。
data class MyUByte(
val value: UByte
)
并有:-
@TypeConverter
fun myUByteToInt(myUByte: MyUByte): Int = myUByte.value.toInt()
@TypeConverter
fun intToMyUByte(value: Int): MyUByte = MyUByte(value.toUByte())
最后:-
@Entity
data class UInt8(
@PrimaryKey(autoGenerate = true)
var key: Int,
var name: String = "uint8-test",
var testvalue: MyUByte = MyUByte(0.toUByte()),
var size: Int = 1,
var readOnly: Boolean = true
)
然后 TypeConverters 就不会被忽略,编译就可以了。