Hierarchy of data classes

I have a hierarchy of data classes:

                 SchoolWorker
                 /                     \
         Teacher              Principle     
data class SchoolWorker(val id: Long, val name: String)
data class Teacher(val className:String)
data class Principle(val numberOfReports:Int)

I thought to use data class but it does not really work. If SchoolWorker is data class, then all children needs to pass its fields, but if children are data classes, its constructor can only have fields so it is not clear how to pass values to super constructor.

Of course I can give up on data classes and just use classes but, then I loose equals and hashCode, and now I need to generate them which looks ugly compare to lombok+java.

Is there a way to model domain objects as hierarchy of data classes?

Data classes cannot be abstract, open, sealed, or inner.

From Data classes | Kotlin Documentation

This means data classes can not be inherited. The data class can however inherit from a non-data class.

And as for the constructor question: use a secondary constructor to receive the parameter that need to be passed on to the base class.

From the description it looks like you wanted to use either abstract or sealed class (or interface) here:

sealed class SchoolWorker {
	abstract val id: Long
	abstract val name: String
}

data class Teacher(
	override val id: Long,
	override val name: String,
	val className: String
) : SchoolWorker()

data class Principle(
	override val id: Long,
	override val name: String,
	val numberOfReports: Int
) : SchoolWorker()
1 Like