带条件的 Kotlin 复制函数

lou*_*ros 3 copy kotlin

有没有办法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
        )
    )

}
Run Code Online (Sandbox Code Playgroud)

Epi*_*rce 5

您可以将takeIf函数用于内联条件。null如果谓词为假,它会返回,这让你可以将它链接到一个?:.

firstName = dto.firstName.takeIf { it.isNotEmpty() } ?: user.firstName
Run Code Online (Sandbox Code Playgroud)

它可以很好地与let.

val something = other.takeIf { it.someBool }?.let { Something(it) } ?: throw Exception()
Run Code Online (Sandbox Code Playgroud)

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

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)
    }
}
Run Code Online (Sandbox Code Playgroud)