DEV Community

Discussion on: Mapping JPA entities with Kotlin

Collapse
 
livioribeiro profile image
Livio Ribeiro

Sorry for the late reply.

I did some tests and found out that inheritance with data classes can be tricky, specially if you have to set fields on the base class, since you cannot have arguments on the primary constructor that are not properties.

If the fields in the base class are auto generated (like Id, creation date), you can do something like this:

import java.time.LocalDate
import java.time.LocalDateTime

open class Base(
        val id: Int? = null,
        val dateCreated: LocalDateTime = LocalDateTime.now(),
        val lastUpdated: LocalDateTime = LocalDateTime.now(),
)

data class Task(
        var name: String,
        var description: String? = null,
        var dueDate: LocalDate? = null,
        var done: Boolean = false
) : Base()

For more complex cases, I believe it is better to use normal classes.