Assuming I have a data class like this
data class PersonDTO(
val id: Long?,
val firstName: String,
val lastName: String,
)
which I then persist in the database on this entity
@Entity
@Table(name = "person")
class Person(
@Column(name = "first_name", nullable = true)
var firstName: String? = null,
@Column(name = "last_name", nullable = true)
var lastName: String? = null,
) {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
val id: Long = 0
}
like so
personRepository.save(
Person(
firstName = personDto.firstName,
lastName = personDto.lastName
)
)
Since firstName and lastName are nullable, I want the data class PersonDTO to behave the following way: If firstName is of length === 0, return null for firstName (and the same for lastName).
Is there a way to achieve this?
>Solution :
I would just add new properties to the data class:
data class PersonDTO(
val id: Long?,
val firstName: String,
val lastName: String,
) {
val nonEmptyFirstName: String?
get() = firstName.takeUnless { it.isEmpty() }
val nonEmptyLastName: String?
get() = lastName.takeUnless { it.isEmpty() }
}
personRepository.save(
Person(
firstName = personDto.nonEmptyFirstName,
lastName = personDto.nonEmptyLastName
)
)
Or write a function to convert to a Person directly.
fun PersonDTO.toPerson() = Person(
firstName = firstName.takeUnless { it.isEmpty() },
lastName = lastName.takeUnless { it.isEmpty() }
)
If this doesn’t have to be a data class, you can achieve this without using any extra properties. The properties firstName and lastName are nullable, but the constructor does not accept null.
class PersonDTO(
val id: Long?,
firstName: String,
lastName: String,
) {
val firstName: String? = firstName
get() = field?.takeUnless { it.isEmpty() }
val lastName: String? = lastName
get() = field?.takeUnless { it.isEmpty() }
}