我想在我的 Room 数据库中保存一个对象,其中一个变量可以是 on 类型或另一个。我认为密封类是有意义的,所以我采用了这种方法:
sealed class BluetoothMessageType() {
data class Dbm(
val data: String
) : BluetoothMessageType()
data class Pwm(
val data: String
) : BluetoothMessageType()
}
甚至这个,但没有必要。我发现这个给了我更多的错误,因为它不知道如何处理打开的 val,所以如果我找到第一个版本的解决方案,无论如何我都会很高兴。
sealed class BluetoothMessageType(
open val data: String
) {
data class Dbm(
override val data: String
) : BluetoothMessageType()
data class Pwm(
override val data: String
) : BluetoothMessageType()
}
然后是实体类
@Entity(tableName = MESSAGES_TABLE_NAME)
data class DatabaseBluetoothMessage(
@PrimaryKey(autoGenerate = true)
val id: Long = 0L,
val time: Long = Instant().millis,
val data: BluetoothMessageType
)
我还创建了一个 TypeConverter 来将其转换为字符串,因此我认为这不是问题。
首先,这可能吗?我认为这应该以与抽象类类似的方式起作用,但我也没有设法找到一个可行的解决方案。如果不可能,当我想保存一些可能是一种或另一种类型的数据(如果不是密封类)时,我应该采取哪种方法?