A Retrofit suspend method declared with a nullable Receipt return type throws KotlinNullPointerException on a 204 No Content; why, and what should it declare instead?
answer
- 204 and 205 carry no body
- the converter is skipped
- suspend nullability is not detected
- Response<T> lets body() be null
- Unit when no body is expected
basics
~20 sRetrofit returns a null body for 204 and 205, and its suspend support cannot see the ? in Receipt?, so it treats the type as non-null and throws KotlinNullPointerException. Declare Response<Receipt> and check body(), or Unit when no body ever comes.
solid answer
~40 sFor a 204 or 205, Retrofit closes the body without running the converter and produces a successful `Response` whose body is null. A suspend method that returns the body type then goes through Retrofit's non-null await path, which throws `KotlinNullPointerException` with a message like "Response from com.example.PaymentsApi.confirm was null but response body type was declared as non-null". The `?` in `Receipt?` does not help: Retrofit reads the method's generic Java signature, which carries no Kotlin nullability, and as of Retrofit 3.0.0 it still does not detect a nullable suspend return type. The 2.6.0 changelog already said suspend support covers non-null body types only. Declare `Response<Receipt>` when the endpoint sometimes sends a body and sometimes 204, or `Unit` when it never sends one.
code
kotlin · 25 linesimport retrofit2.HttpException
import retrofit2.Response
import retrofit2.http.DELETE
import retrofit2.http.POST
import retrofit2.http.Path
data class Receipt(val id: String, val total: Long)
interface PaymentsApi {
// 200 with a Receipt the first time, 204 when the payment was already confirmed
@POST("payments/{id}/confirm")
suspend fun confirmBroken(@Path("id") id: String): Receipt? // 204 -> KotlinNullPointerException
@POST("payments/{id}/confirm")
suspend fun confirm(@Path("id") id: String): Response<Receipt> // 204 -> body() == null
@DELETE("cards/{id}")
suspend fun removeCard(@Path("id") id: String) // Unit: 204 returns normally
}
suspend fun confirmPayment(api: PaymentsApi, id: String): Receipt? {
val response = api.confirm(id)
if (!response.isSuccessful) throw HttpException(response)
return response.body() // null on 204: the payment was already confirmed
}go deeper
Recall that 204 No Content has no body, so a declaration that promises a Receipt has nothing to hand back.
Explain that Retrofit skips the converter for 204 and 205 and yields a null body, and which declarations, Response<T> or Unit, can carry that.
Diagnose from the exception message, which names the service and method, and explain that Retrofit 3.0.0 still cannot read Kotlin nullability on suspend methods, so the ? is ignored.
Agree a convention with the backend: endpoints that may answer 204 are declared Response<T> or Unit, and API review flags a plain body type on any of them.
## The symptom A checkout flow calls a **confirm payment** endpoint. The first time, the server answers **200** with a `Receipt`; if the payment was already confirmed, it answers **204 No Content**. The service method looks reasonable: - `@POST("payments/{id}/confirm") suspend fun confirm(@Path("id") id: String): Receipt?` Yet every 204 crashes, or lands in a generic error handler, with a **`KotlinNullPointerException`** whose message reads roughly: *Response from com.example.PaymentsApi.confirm was null but response body type was declared as non-null*. The nullable `?` was meant to cover exactly this case. ## What Retrofit does with 204 and 205 Retrofit's call implementation handles these two codes before any converter runs: 1. It checks the status: 204 and 205 are inside 200 to 299, so the call is **successful**. 2. For 204 or 205 it **closes the body** and builds `Response.success(null, ...)`, a successful response with a **null body**. 3. The converter is **never invoked**, so no JSON library ever sees the empty input. So the null is not a parsing failure; it is Retrofit faithfully reporting "success, no body". ## Why the suspend method throws A suspend service method is adapted onto a `Call` and awaited. Retrofit picks one of three internal await paths when it builds the method: - **Unit**: the declared type is `Unit`, so the nullable path is used and a null body completes normally. - **Nullable body**: would accept null, but Retrofit never selects it. The flag that would choose it is fixed at false, next to a TODO about reading Kotlin metadata to learn whether the return type is nullable. - **Non-null body**: used for every other body type, `Receipt?` included. If `isSuccessful` is true and the body is null, it throws `KotlinNullPointerException` naming the service and method. Because `KotlinNullPointerException` is a `RuntimeException`, a generic error handler around the call usually catches it and shows a vague failure, which is why the bug can survive for a long time: the payment was confirmed, but the screen reports an error. The reason Retrofit ignores the `?` is mechanical: Retrofit inspects the method through Java reflection, and a Java generic signature has **no notion of Kotlin nullability**. `Receipt` and `Receipt?` look identical. The **2.6.0** changelog stated that suspend support "only supports non-null response body types", and the **3.0.0** source still behaves that way. ## Declarations that work | Declaration | 200 with a `Receipt` | 204 No Content | |---|---|---| | `suspend fun confirm(...): Receipt` | returns the receipt | throws `KotlinNullPointerException` | | `suspend fun confirm(...): Receipt?` | returns the receipt | throws `KotlinNullPointerException` | | `suspend fun confirm(...): Response<Receipt>` | `Response` with the body | successful `Response`, `body()` null | | `suspend fun confirm(...)` (returns `Unit`) | body discarded | returns normally | | `fun confirm(...): Call<Receipt>` | `onResponse`, body present | `onResponse`, `body()` null | - Choose **`Response<Receipt>`** when the endpoint may or may not send a body; check `isSuccessful`, then treat a null `body()` as the no-content case. - Choose **`Unit`** when the endpoint never sends a body you need, such as a delete. Retrofit's built-in `Unit` converter discards any body a 200 might carry. - A `@HEAD` method has no choice: Retrofit rejects it when it builds the method unless it returns `Void` or `Unit`. ## Where else a null body bites The check that throws is not specific to 204. It fires for **any successful response whose converted body is null**. `Converter.convert` is allowed to return null, so a converter that maps a 2xx body to null, such as a JSON literal `null` for some converters, triggers the same exception on a non-null declaration. The message helps: it names the **service class and method**, read from the request's `Invocation` tag, which points straight at the declaration to fix. ## Fixing it across a codebase - Grep service interfaces for endpoints the backend documents as returning 204, and declare them `Response<T>` or `Unit`. - Test it end to end against a mock server that answers 204 for the endpoint: a unit test with a hand-written fake service never runs Retrofit's await path, so it cannot reproduce the exception. - Do not paper over it by catching `NullPointerException` around calls; that also hides real bugs. - Keep the mapping in one place: a repository that turns a null `body()` into an explicit "already confirmed" result is easier to test than a scattered null check.
- Why does the same 204 not crash a Retrofit suspend method that returns Unit?Retrofit recognises `Unit` as the response type when it builds the method and routes the call through its nullable await path, which accepts a null body and completes normally. The built-in `Unit` converter also discards any body a 200 might carry, so `Unit` suits endpoints whose result you only need as success or failure.
- Can a 200 response trigger the same KotlinNullPointerException in Retrofit?Yes. The check runs on any successful response whose converted body is null, and `Converter.convert` may return null. If the registered converter turns a 2xx body into null, for example a JSON literal null with some converters, the non-null await path throws the same exception, naming the service and method.
- Declaring Receipt? tells Retrofit the suspend method's body may be null.
- Retrofit runs the JSON converter on the empty 204 body and it fails.
- A 204 makes a Retrofit suspend method throw HttpException.
- Response<Receipt> throws on a 204 just like the body type does.
- Catching NullPointerException around each call is the proper fix.
Assumes Retrofit 3.0.0, whose suspend methods still treat the declared body type as non-null; the 2.6.0 changelog limited suspend support to non-null body types.