What does nullable void mean in Kotlin?

Viewed 103

If I generate callback code in android studio for a retrofit2 enqueue call I get

object : Callback<Void?> {
    override fun onResponse(call: Call<Void?>, response: Response<Void?>) {...}
    ...
}

The code in my retrofit2 interface is just Void

@POST("api/v1/users")
fun post(@Body body: UserRequestData): Call<Void>

Normally in Kotlin ? just means nullable, which makes sense for other types. But what is this type Void? and how is it different from just Void ?

1 Answers

From the Java docs:

The Void class is an uninstantiable placeholder class to hold a reference to the Class object representing the Java keyword void.

In general, void is replaced with Unit in Kotlin.:

The type with only one value: the Unit object. This type corresponds to the void type in Java.

However, when the use of Void is required due to it being used as a generic parameter, consider the following:

Response<T> has a function called body() that returns a generic T. In your case, For Response<Void>.body() it will return null. In Java, this is fine, because Void means "not relevant" so null is an appropriate response. But Kotlin has null-safetly, so to accurately represent that null is possible, Response<Void?> is necessary, even though it's slightly counter-intuitive.

A better design if the library was pure Kotlin would be Response<Nothing>, which should produce an error when you call body().

Related