首页 > 解决方案 > 在 Kotlin DTO 中使用 Java 可选

问题描述

目前我Optional在我的 Kotlin DTO 中使用 Java 8,如下所示:

class dto {
    var prop1: String? = null

    var prop2: Optional<String>? = null
}

它的目的是对于某些属性,例如prop2我还想允许在请求中删除。所以prop2DTO中的值理解如下:

null =>什么都不做
非空可选=>更新值
空可选=>删除值(将值设置为null)

然后在代码中的某个时刻,我正在执行以下操作:

dto.prop2?.let {
    // since it is not null, then we either need to update or delete value
    if (it.isPresent) {
        // indicates update value
        entity.prop2 = it.get()
        // then entity will be saved in DB and column will be updated
    } else {
        // indicates delete/erase value
        entity.prop2 = null
        // then entity will be saved in DB and column value will be set to null
    }
}

所以我现在的问题是有一个Kotlinish无需使用 Java 就可以实现相同的行为Optional吗?因为我认为这种方式很复杂,这也意味着必须isPresent检查代码中的许多部分。

标签: javakotlinoptional

解决方案


也许您可以创建一个更新操作的密封类层次结构来对此进行建模。这应该使您的代码非常可读。像这样的东西:

sealed class UpdateableProperty<out T>
data class Update<T>(val value: T) : UpdateableProperty<T>()
object DoNothing : UpdateableProperty<Nothing>()
object Delete : UpdateableProperty<Nothing>()

data class Dto (
   val prop1: UpdateableProperty<String>,
   val prop2: UpdateableProperty<Int?>
)

现在,您可以匹配属性来决定要做什么:

when(val prop = dto.prop1) {
    is Update -> repo.update(prop.value)
    is Delete -> repo.delete()
    is DoNothing -> { /* Do nothing */ }
}

推荐阅读