I want to use the @CreatedDate annotation in a kotlin data class. All attributes should be initialized as immutable (val). The problem is, that the implementation is not able to handle immutable variables. The correct date will not be set and the variable is null. With mutable variables the implementation is able to set the date.
Example:
@Entity
@EntityListeners(AuditingEntityListener::class)
data class Test(
@Id
@GeneratedValue(generator = "UUID")
@GenericGenerator(name = "UUID", strategy = "org.hibernate.id.UUIDGenerator")
@Column(name = "id", updatable = false, nullable = false)
val id: UUID? = null,
val text: String,
@CreatedDate
@Column(updatable = false, nullable = false)
var createdAt: LocalDateTime?,
...
Is there any special plugin for the kotlin compiler to solve the problem or is it ok to use val and var in the same data class?
Using val
and var
is perfectly acceptable.
Think of an example where you only want to be able to set attributes when you instantiate an object, but you don't wan users to be able to change those attributes later.
It's like allowing for the assignment in the constructor and then only providing a getter method for that attribute.
If you display the actual bytecode (convert the kotlin to java equivalent), you'll see exactly that. There are no setter methods for your val
attributes.
Instructions for Intellij:
Display bytecode: Tools -> Kotlin -> Show Kotlin Bytecode
Or just: cmd + shift + A (Mac) / ctrl + shift + A (Windows) and type “Kotlin Bytecode”