java - 在 Kotlin DTO 中使用 Java 可选
问题描述
目前我Optional
在我的 Kotlin DTO 中使用 Java 8,如下所示:
class dto {
var prop1: String? = null
var prop2: Optional<String>? = null
}
它的目的是对于某些属性,例如prop2
我还想允许在请求中删除。所以prop2
DTO中的值理解如下:
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
检查代码中的许多部分。
解决方案
也许您可以创建一个更新操作的密封类层次结构来对此进行建模。这应该使您的代码非常可读。像这样的东西:
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 */ }
}
推荐阅读
- angular - 在根工作区中提供时在 bazel 工作区中引用 angular.json 不是一种选择
- webpack - 加载资源失败:net::ERR_FILE_NOT_FOUND iconfont.css
- asp.net-core - 挑战方法不重定向到指定的 url
- node.js - ProxyServer 在 Got Package http 请求 Nodejs 中不起作用
- keras - Keras自定义多输入中的Nonetype错误
- firebase - 错误“[core/no-app] No Firebase App '[DEFAULT]' has been created - call Firebase.initializeApp()”抛出
- javascript - WebDriverIO :: 错误:setValue 不是函数”
- oracle - Oracle Apex,如何在选中复选框的 Oracle Apex 交互式报告中获取数据
- azure - 将 Microsoft(个人和工作 Azure AD)OIDC 集成到 AWS Cognito
- android - IONIC:使用文件插件将文件从内部存储复制到应用程序目录后文件大小增加