Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Kotlin copy function with conditions

Tags:

copy

kotlin

Is there a way to use copy Kotlin function and use the original object value property in case of a conditional state non verified ? Or a similar function that does that ?

Example:

data class UserEntity(
    id = String,
    email = String,
    firstName = String,
    lastName = String
)

data class UserUpdate(        
    firstName = String?,
    lastName = String?
)

@Service
class UserService(userRepository: UserRepository) {

    fun update(id: String, dto: UserUpdate) = userRepository.save(
        userRepository.findById(id).copy(
            // *it* is not available as the initial object the  
            // copy function is called from.
            firstName = dto.firstName ?: it.firstName,
            // I'd like something like:
            lastName = dto.lastName ?: keepTheOriginalLastNameProperty
        )
    )

}
like image 708
louis amoros Avatar asked Nov 15 '25 05:11

louis amoros


1 Answers

You can use takeIf function for inlining conditions. It returns null if the predicate is false, which lets you chain it into a ?:.

firstName = dto.firstName.takeIf { it.isNotEmpty() } ?: user.firstName

It can be combined quite well with let.

val something = other.takeIf { it.someBool }?.let { Something(it) } ?: throw Exception()

EDIT: as response to your edit, unfortunately the best option I see is this:

fun update(id: String, dto: UserUpdate) = run {
    userRepository.findById(id).let { user ->
        val firstName = dto.firstName ?: user.firstName
        val lastName = dto.lastName ?: user.lastName
        user.copy(firstName = firstName, lastName = lastName)
    }.let {
        userRepository.save(it)
    }
}
like image 102
EpicPandaForce Avatar answered Nov 17 '25 20:11

EpicPandaForce



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!