Skip to content
Advertisement

Using Java Optional in Kotlin DTOs

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.

Advertisement

Answer

In order to modify only some fields of a resource I would use the HTTP PATCH method. You can send a map in the body of your request only with the fields that you want to modify.

If you want to set prop2 to null, send {"prop2":null}. If you want to modify it to a new value, send {"prop2":"new value"}. If you want to do nothing, just don’t send prop2 in the map.

But if you prefer a more type safe version, you can create a DTO like that:

data class UpdateProp2DTO(
    val id: String
    val prop2: String?
)

You’re going to use use this DTO only if you want to change prop2, otherwise just don’t use it.

For the PATCH method it only makes sense to create a DTO with fewer properties than the resource. If you want to be able to update all properties at once you have the PUT method for that and then you just need to replace the whole resource with the DTO provided in the request body.

You can find more information in the accepted answer of this question: Rest api – update single field of resource. It points to a link describing how to do that with Spring.

Advertisement