Affects: All versions
Context
I like that <T> ResponseEntity<T> ResponseEntity.of(Optional<T> body)
gives a 200 OK with a body if it is present inside the optional and a 404 for an empty Optional.
Problem
However, sometimes you cannot or do not want to deal with Optional
(for instance when using Kotlin) but still want to have a useful method like this.
Current workaround
The current workaround would be to just wrap it inside an Optional
:
ResponseEntity.of(Optional.ofNullable(entity))
but this is pretty ugly and still creates an extra intermediate Optional
object.
Proposal
My proposal would be to add a method:
<T> ResponseEntity<T> ResponseEntity.ofNullable(T body)
which can be used by both Java and Kotlin to turn a nullable object into a 200 OK with body or 404.
The implementation would be pretty straightforward:
public static <T> ResponseEntity<T> ofNullable(T body) {
if (body == null) {
return notFound().build();
}
return ResponseEntity.ok(body);
}
Comment From: sdeleuze
The use case seems valid to me, and I have don't have a better proposal for the name, we should just make sure to annotate correctly the parameter:
public static <T> ResponseEntity<T> ofNullable(@Nullable T body) {
if (body == null) {
return notFound().build();
}
return ResponseEntity.ok(body);
}
@poutsma @rstoyanchev Are you ok to introduce this variant?
Comment From: poutsma
Sounds good to me.