5

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?

Sebastian A.
  • 105
  • 1
  • 8
  • Sure it is. Why do you think it's not ok? – Simon Martinelli Aug 12 '19 at 10:21
  • 1
    If you just want it set to the moment of creation, you don't need a special annotation: `@Column(updatable = false, nullable = false) val createdAt: LocalDateTime = LocalDateTime.now()`. – gidds Aug 12 '19 at 17:16
  • 1
    I also used this explicit initialization first, and some time ago I was told to replace it with @CreatedDate annotation. I tried to do it many times but I wonder how could you save your entity, because each time I stuck with an error `No value passed for parameter 'createdAt'`. – Oleg Bolden Jul 20 '21 at 10:16

1 Answers1

0

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”
Jolley71717
  • 678
  • 1
  • 8
  • 20