Reputation: 6448
I've got an issue creating entities in Kotlin. In particular, it's about passing data to a super class. Find an example below.
I've got an abstract super class called Trackable
that classes can extend. It has a user
property that stores who has created that particular object.
abstract class Trackable(
var createdBy: User
) : Persistable()
An class called Contract
would now implement the Trackable
super class with a compile-time error for the time being:
@Entity
data class Contract(
var creationDate: LocalDateTime
) : Trackable() // compile error, no user passed here
So, as the User
is a mandatory field in Trackable
, I have to pass a User
object to the Trackable
constructor. What came first into my mind was creating a transient property called creator
that I pass on to the Trackable
.
@Entity
data class Contract(
@Transient val creator: User,
var creationDate: LocalDateTime
) : Trackable(creator)
However, domain-wise this seems to be a very dirty solution as it pollutes my Contract
.
Having started with Kotlin recently I'm still lacking of appropriate and reasonable patterns to use. Could anyone please help me out with this?
Upvotes: 3
Views: 1200
Reputation: 2821
Data classes don't work best with inheritance, it might be better to use composition, but if you really want to use inheritance then IMHO best way to do it is following:
Declare abstract class with abstract fields:
abstract class Trackable : Persistable(){
abstract var createdBy: User
}
Extend abstract class and override property inside data class:
data class Contract(
override var createdBy: User,
var creationDate: LocalDateTime) : Trackable()
This way you avoid having duplicate property while having ability to access that property from parent
class but it is actually a member of children
, from my perspective this is best solution as you keep all benefits of data class
, but take it with grain of salt as it is subjective.
Upvotes: 1