Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Convert values of data class

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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() }
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading