子类房间实体
Subclassing Room Entities
有没有办法对 Room 中的实体进行子类化?
我有车entity
@Entity(tableName = "cars")
data class Car(
@PrimaryKey @ColumnInfo(name = "vin") val vin: String,
val manufacturer: String,
val model: String,
val color: String,
val modelYear: Int,
val trim: String = ""
) {
override fun toString() = String.format("%s %s %s %s", modelYear, manufacturer, model, trim)
}
但我想将 manufacturer
、model
和 modelYear
移动到 Vehicle
实体并让 Car
继承它。
我尝试用这些字段创建一个 Vehicle
实体并使用 data class Car : Vehicle
,但没有编译。错误是 This type is final and cannot be inherited
在kotlin
中,所有class默认都是final。
来自Docs
The open annotation on a class is the opposite of Java's final: it
allows others to inherit from this class. By default, all classes in
Kotlin are final
, which corresponds to Effective Java, 3rd Edition,
Item 19: Design and document for inheritance or else prohibit it.
所以你需要添加 open
关键字所以使用
open class Vehicle(..){...}
然后
data class Car(...): Vehicle(..){}
旁注:如果你试图继承 data
classes 那么你就不能在 Kotlin 中继承 data
class 因为像 copy
这样的方法数据 class 是最终的,不能被子 class 覆盖(在这种情况下是 data
class 所以它会自动完成)并且很难实现其他方法就像 equals
当 class 层次结构随着不同的数据成员呈指数增长时,尽管您可以通过将非数据父级设置为 class 或 abstract
class[= 来避免所有这些冲突24=]
有没有办法对 Room 中的实体进行子类化?
我有车entity
@Entity(tableName = "cars")
data class Car(
@PrimaryKey @ColumnInfo(name = "vin") val vin: String,
val manufacturer: String,
val model: String,
val color: String,
val modelYear: Int,
val trim: String = ""
) {
override fun toString() = String.format("%s %s %s %s", modelYear, manufacturer, model, trim)
}
但我想将 manufacturer
、model
和 modelYear
移动到 Vehicle
实体并让 Car
继承它。
我尝试用这些字段创建一个 Vehicle
实体并使用 data class Car : Vehicle
,但没有编译。错误是 This type is final and cannot be inherited
在kotlin
中,所有class默认都是final。
来自Docs
The open annotation on a class is the opposite of Java's final: it allows others to inherit from this class.
By default, all classes in
Kotlin are final
, which corresponds to Effective Java, 3rd Edition, Item 19: Design and document for inheritance or else prohibit it.
所以你需要添加 open
关键字所以使用
open class Vehicle(..){...}
然后
data class Car(...): Vehicle(..){}
旁注:如果你试图继承 data
classes 那么你就不能在 Kotlin 中继承 data
class 因为像 copy
这样的方法数据 class 是最终的,不能被子 class 覆盖(在这种情况下是 data
class 所以它会自动完成)并且很难实现其他方法就像 equals
当 class 层次结构随着不同的数据成员呈指数增长时,尽管您可以通过将非数据父级设置为 class 或 abstract
class[= 来避免所有这些冲突24=]