spring-framework
spring-framework copied to clipboard
Add ResponseEntity.ofNullable() to deal with non-Optional nullable objects
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);
}