Kotlin复制功能有条件

问题描述 投票:3回答:1

有没有办法使用copy Kotlin函数并在条件状态未验证的情况下使用原始对象值属性?或者类似的功能呢?

例:

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
        )
    )

}
kotlin copy
1个回答
4
投票

您可以使用takeIf函数进行内联条件。如果谓词为false,则返回null,这允许您将其链接到?:

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

它可以与let很好地结合起来。

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

编辑:作为对您的编辑的回应,遗憾的是我看到的最佳选择是:

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)
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.