Property in class header vs in class body

Viewed 42

I have an abstract class entity.

abstract class AbstractEntity {
    @Id
    @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "id")
    @SequenceGenerator(name = "id", sequenceName = "id_sequence", allocationSize = 1000)
    var id: Long? = null

    @Version
    private var version: Int = 0


    @NotNull
    var createdDate = ZonedDateTime.now()!!
}

And I have a class(javax.persistence Entity ) that inherits from AbstarctEntiy

@Entity
@Table(schema = "query")
data class Query(
    var name: String?,
) : AbstractEntity()

Is there any difference between using users in class header and in class body as in the following two codes?

1

@Entity
@Table(schema = "query")
data class Query(
    var name: String?,
    @OneToMany(mappedBy = "id", fetch = FetchType.EAGER)
    var users : List<Username> = mutableListOf()
) : AbstractEntity()

2

@Entity
@Table(schema = "query")
data class Query(
    var name: String?,
) : AbstractEntity() {
    @OneToMany(mappedBy = "id", fetch = FetchType.EAGER)
    var users : List<Username> = mutableListOf()
}
1 Answers

There is a difference between passing an item through the constructor, and setting it as a property because you are using a data class to hold those.

While in example 1 and 2 Kotlin is generating a getter and a setter for both the user and name fields, main benefits of using a data class only get leveraged for items passed through the constructor.

In Example 1, because it's a data class Kotlin overrides the 'copy', 'toString', 'hashCode' and 'equals' classes for BOTH the properties you're passing into the constructor. So just as an example, the 'toString' function would look like so in the decompiled java code

   @NotNull
   public String toString() {
      return "Query(name=" + this.name + ", users=" + this.users + ")";
   }

In Example 2, you only get this benefit for the name property you are passing into the constructor, but not for the user list. In this case, the toString() and all the other functions I mentioned would only take into consideration name

   public String toString() {
      return "Query1(name=" + this.name + ")";
   }

This is true for all the rest of copy() hashCode(), and equals()

If you care about Kotlin handling these for both user and name then pass both through in the constructor. Otherwise, it doesn't matter.

Related