Skip to content

ResponseEntity body nullability issue with Kotlin #36236

@alfonsoristorato

Description

@alfonsoristorato

Hi there, since Spring 4 and the introduction of JSpecify I am no longer able to declare some nullable types in ResponseEntity.

For example, such an endpoint:

@RestController
class HelloController {
    @GetMapping("/hello")
    fun hello(): ResponseEntity<String?> {
        val maybeHello :String? = "hey"
        return ResponseEntity.ok(maybeHello)
    }
}

would return a ResponseEntity with body String, or a ResponseEntity with null body (according to whatever logic determines whether the body is null or not).
Leaving alone as to whether or not this is a recommended Rest endpoint, I would expect this to compile properly, especially due to ResponseEntity contract, which is as follows (current version 7.0.2):

	public static <T> ResponseEntity<T> ok(@Nullable T body) {
		return ok().body(body);
	}

However, although the IDE does not recognise this as an error (cause I assume it should not be, given @Nullable), when I compile I get the following error:

exception: src/main/kotlin/.../Application.kt:19:33: error: type argument is not within its bounds: must be subtype of 'Any'.
exception:     fun hello(): ResponseEntity<String?> {
exception:                                 ^^^^^^^
exception: src/main/kotlin/.../Application.kt:21:16: error: return type mismatch: expected 'ResponseEntity<String?>', actual 'ResponseEntity<String>'.
exception:         return ResponseEntity.ok(maybeHello)
exception:                ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

I understand that I can completely omit ResponseEntity and just return the nullable body, but I am confused as to why Jsepcify is not recognising this kotlin nullability.
I have read that there are still teething issues when it comes to Jspecify and generics, but I wonder if this would fall under this category, and if so what is your recommendation for the short term.

Metadata

Metadata

Assignees

No one assigned

    Labels

    in: webIssues in web modules (web, webmvc, webflux, websocket)status: waiting-for-triageAn issue we've not yet triaged or decided on

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions