Currently I'm using Java 8's Optional
in my Kotlin DTOs as follows:
class dto {
var prop1: String? = null
var prop2: Optional<String>? = null
}
The purpose of it is that for some properties like prop2
I want to also allow delete in the request. So the value of prop2
in the DTO is understood as follows:
null => do nothing
non-empty optional => update value
empty optional => delete value (set value to null)
Then at some point in the code I'm doing the following:
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
}
}
So my question now is there a Kotlinish of achieving the same behavior without having to use Java Optional
? As I think it is complicated in this way and this also implies having to do isPresent
check over many parts in the code.