在未验证条件状态的情况下,是否可以使用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
)
)
}
答案 0 :(得分:4)
您可以使用takeIf
函数来内联条件。如果谓词为假,它将返回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)
}
}