Alan
Alan

Reputation: 9471

Subclassing Room Entities

Is there a way to subclass entities in Room?

I have an car 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)
}

But I want to move the manufacturer, model, and modelYear to a Vehicle entity and have the Car inherit from it.

I tried creating a Vehicle entity with those fields and use data class Car : Vehicle, but does not compile. The error is This type is final and cannot be inherited

Upvotes: 4

Views: 1867

Answers (1)

Pavneet_Singh
Pavneet_Singh

Reputation: 37404

In kotlin, all classes are final by default.

From 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.

so you need to add open keyword so use

open class Vehicle(..){...}

then

data class Car(...): Vehicle(..){}

Side Note: if you trying to inherit data classes then simply you cannot inherit data class in Kotlin because method like copy in data class are final which cannot be overridden by the child class (which in this case is data class so it will do it automatically) and it's hard to implement other methods like equals when class hierarchy grows exponentially with different data members though you can avoid all this collision by making non-data parent class or abstract class

Upvotes: 2

Related Questions