Retrofit throws KotlinNullPointerException when a suspend function gets a 204 or 205. The message says the “response body type was declared as non-null”. The crash comes from two separate behaviors in Retrofit. First, Retrofit never runs your converter for those two status codes. It hands back a successful response with a null body. Second, Retrofit can’t read Kotlin nullability on a suspend function’s return type. So adding ? changes nothing. The call still goes through the non-null path that throws. A typical trigger is a backend change. A DELETE endpoint that used to return JSON starts returning 204 No Content. Every delete then crashes. The fix depends on the endpoint. If it never returns a body, declare the function as returning Unit. That works on Retrofit 2.10.0 and newer. If it can return a body or a 204, return Response<T>. Treat a null body as “no content”.
A notes app that crashes on delete after a backend deploy
The running example is a notes app. Deleting a note calls the server, then removes the local row. The server used to answer with a small JSON object. The app code below was written against that contract.
@Serializable
data class DeleteResult(val id: String, val deleted: Boolean)
interface NotesApi {
@DELETE("notes/{id}")
suspend fun deleteNote(@Path("id") id: String): DeleteResult
}
class NotesRepository(private val api: NotesApi, private val dao: NoteDao) {
suspend fun delete(id: String) {
api.deleteNote(id)
dao.deleteById(id)
}
}
Then the backend team tidies up its API. DELETE now returns 204 with no body. That’s a valid answer. RFC 9110 defines 204 as success with no content in the response. No app code changed. The next delete crashes with this.
kotlin.KotlinNullPointerException: Response from NotesApi.deleteNote was null but response body type was declared as non-null
The server has already deleted the note. The exception skips dao.deleteById, so the note stays on screen. If the backend answers 404 for a missing note, the user’s second tap now fails differently.
Retrofit skips the converter and returns a null body for 204 and 205
The first cause sits in OkHttpCall.parseResponse. In the Retrofit 2.11.0 source, a 204 or 205 closes the raw body and returns early. It builds Response.success(null, rawResponse) without calling any converter. The kotlinx.serialization converter never sees the request. So nothing can fail during parsing. Nothing can supply a default object either.
This is old, intended behavior. Issue #2867 was filed in August 2018 and is still open. It asks for 204 and 205 to reach the converter. The response is still a success, because 204 is a 2xx code. So the null body travels on to the code that adapts the call for coroutines.
Why the response body type was declared as non-null error ignores ?
The second cause defeats the obvious fix. For a suspend function, Retrofit picks one of three await paths. HttpServiceMethod sets a flag for Unit and a flag for nullable bodies. The nullable flag starts as false and is never set. The line that would set it is a TODO comment about reading Kotlin metadata. So any non-Unit body type takes the non-null path.
That path is await() in KotlinExtensions.kt. On a successful response with a null body, it builds the KotlinNullPointerException above. The message uses the service and method names from the request’s Invocation tag. Issue #3075, filed in April 2019, reports that ? and @Nullable both fail to help. It’s still open. The trunk source still has the same TODO.
A small repro shows both causes. It uses OkHttp’s MockWebServer 4.12.0, kotlinx.serialization 1.9.0 and Jake Wharton’s serialization converter 1.0.0. It adds three more declarations of the same endpoint to the NotesApi above. Then it calls each one against a 204.
interface NotesApi {
@DELETE("notes/{id}")
suspend fun deleteNote(@Path("id") id: String): DeleteResult
@DELETE("notes/{id}")
suspend fun deleteNoteNullable(@Path("id") id: String): DeleteResult?
@DELETE("notes/{id}")
suspend fun deleteNoteUnit(@Path("id") id: String)
@DELETE("notes/{id}")
suspend fun deleteNoteResponse(@Path("id") id: String): Response<DeleteResult>
}
fun main() = runBlocking {
val server = MockWebServer().apply { start() }
val api = Retrofit.Builder()
.baseUrl(server.url("/"))
.addConverterFactory(Json.asConverterFactory("application/json".toMediaType()))
.build()
.create(NotesApi::class.java)
val calls: List<Pair<String, suspend () -> Any?>> = listOf(
"DeleteResult " to { api.deleteNote("n1") },
"DeleteResult?" to { api.deleteNoteNullable("n1") },
"Unit " to { api.deleteNoteUnit("n1") },
"Response<T> " to { api.deleteNoteResponse("n1").let { "code=${it.code()} body=${it.body()}" } },
)
for ((label, call) in calls) {
server.enqueue(MockResponse().setResponseCode(204))
val result = runCatching { call() }
println("204 $label -> " + result.fold({ "OK $it" }, { "${it::class.simpleName}: ${it.message}" }))
}
server.shutdown()
}
We built it with kotlinc 2.4.20 and ran it on JDK 25 against Retrofit 2.11.0. The output:
204 DeleteResult -> KotlinNullPointerException: Response from NotesApi.deleteNote was null but response body type was declared as non-null 204 DeleteResult? -> KotlinNullPointerException: Response from NotesApi.deleteNoteNullable was null but response body type was declared as non-null 204 Unit -> OK kotlin.Unit 204 Response<T> -> OK code=204 body=null
The nullable declaration fails exactly like the non-null one. Retrofit 3.0.0 printed the same four lines. Retrofit 2.9.0 differed in one place. Its Unit line also threw KotlinNullPointerException.
Declare Unit when the endpoint never sends a body
That 2.9.0 result is why the fix has a version floor. The commit that added the Unit path names this exact case. It covers suspend functions on responses without a body. It first shipped in Retrofit 2.10.0, released in March 2024. The changelog lists it as support for Unit as a response type. A suspend function with no declared return type is a Unit function. So the shortest fix is to delete the return type.
interface NotesApi {
// No body expected. Needs Retrofit 2.10.0 or newer.
@DELETE("notes/{id}")
suspend fun deleteNote(@Path("id") id: String)
}
// Only when the same endpoint may answer 200 with JSON or 204 with nothing.
interface NotesApiMixed {
@DELETE("notes/{id}")
suspend fun deleteNote(@Path("id") id: String): Response<DeleteResult>
}
suspend fun NotesApiMixed.deleteOrNull(id: String): DeleteResult? {
val response = deleteNote(id)
if (!response.isSuccessful) throw HttpException(response)
return response.body() // null on 204 and 205
}
We ran both forms against the same mock server on Retrofit 2.11.0 and 3.0.0. The Unit version returned normally on a 204. It did the same on a 200 with an empty body and on a 200 with JSON. A 404 still threw HttpException, so real failures still surface. The mixed version returned null on the 204 and the parsed DeleteResult on the 200.
The Unit form is the better default for a delete. The repository never read DeleteResult anyway. It also keeps working if the backend switches back to 200. Use the Response<T> form only when the caller needs the body on some responses. On Retrofit 2.9.0 or older, Response<Unit> is the safe choice, because Response<T> never goes through the non-null await().
What to say when the stack trace is the whole prompt
In a bug-squash round, you might get the stack trace, the NotesApi interface and one line of context. The interviewer says delete broke “after the backend deploy” with no app release. Our Android debugging interview post covers how that round is scored. Answer in this order.
- Read the message. Retrofit got a successful response with a null body. The declared type is non-null.
- Connect it to the deploy. A successful response with no body points to the backend now sending 204 No Content.
- Name the first cause. Retrofit returns a null body for 204 and 205 without calling the converter.
- Name the second cause. The suspend adapter can’t see Kotlin nullability, so
DeleteResult?takes the same throwing path. - Give the fix. Declare
Uniton Retrofit 2.10.0 or newer. UseResponse<T>if the endpoint can still send a body. - Point out the side effect. The server deleted the note. The local delete never ran. Ask whether the repository should treat 404 on delete as success.
Point 4 rules out the nullable fix before the interviewer suggests it. It also shows you know how Retrofit adapts suspend functions.
Five quick fixes and where each one falls short
- “Make the return type nullable.” The repro shows
DeleteResult?throwing the same exception. Retrofit never reads the?. - “Add a null-on-empty converter factory.” That pattern handles a 200 with an empty body. That case does reach the converter. A 204 returns before any converter runs, so the factory never sees it.
- “Rewrite 204 to 200 in an OkHttp interceptor.” Issue #2867’s first reply suggested this in 2018. With a non-null
DeleteResult, we rewrote 204 to a 200 with anullJSON body. The serialization converter then threwJsonDecodingExceptioninstead. It also changes the status code for every endpoint on that client. Our post on reading bodies in OkHttp interceptors covers a separate trap in that code. - “Catch
KotlinNullPointerException.” It only works if the catch block treats the exception as success. Then a real null-body bug on that call is swallowed too. The fix is to stop declaring a body the server doesn’t send. - “Ask the backend to return 200 again.” That restores the old contract. But 204 was a valid change. The client should accept both.