Kotlin 中的 nullable void 是什么意思?
What does nullable void mean in Kotlin?
如果我在 android studio 中为 retrofit2 排队调用生成回调代码,我得到
object : Callback<Void?> {
override fun onResponse(call: Call<Void?>, response: Response<Void?>) {...}
...
}
我的retrofit2界面中的代码就是Void
@POST("api/v1/users")
fun post(@Body body: UserRequestData): Call<Void>
通常在 Kotlin 中 ?
仅表示可空,这对其他类型有意义。
但是这种 Void?
是什么类型,它与 Void
有何不同?
来自Java docs:
The Void
class is an uninstantiable placeholder class to hold a reference to the Class
object representing the Java keyword void.
一般来说,void
在Kotlin中被替换为Unit
。:
The type with only one value: the Unit
object. This type corresponds to the void
type in Java.
但是,当需要使用 Void
作为通用参数时,请考虑以下事项:
Response<T>
有一个名为 body()
的函数,returns 是一个通用的 T
。在您的情况下,Response<Void>.body()
它将 return null
。在 Java 中,这很好,因为 Void
表示“不相关”,所以 null
是一个合适的响应。但是Kotlin有null-safetly,所以要准确表示null
是可能的,Response<Void?>
是必须的,虽然稍微有点counter-intuitive.
如果库是纯 Kotlin,更好的设计是 Response<Nothing>
,当您调用 body()
.
时应该会产生错误
如果我在 android studio 中为 retrofit2 排队调用生成回调代码,我得到
object : Callback<Void?> {
override fun onResponse(call: Call<Void?>, response: Response<Void?>) {...}
...
}
我的retrofit2界面中的代码就是Void
@POST("api/v1/users")
fun post(@Body body: UserRequestData): Call<Void>
通常在 Kotlin 中 ?
仅表示可空,这对其他类型有意义。
但是这种 Void?
是什么类型,它与 Void
有何不同?
来自Java docs:
The
Void
class is an uninstantiable placeholder class to hold a reference to theClass
object representing the Java keyword void.
一般来说,void
在Kotlin中被替换为Unit
。:
The type with only one value: the
Unit
object. This type corresponds to thevoid
type in Java.
但是,当需要使用 Void
作为通用参数时,请考虑以下事项:
Response<T>
有一个名为 body()
的函数,returns 是一个通用的 T
。在您的情况下,Response<Void>.body()
它将 return null
。在 Java 中,这很好,因为 Void
表示“不相关”,所以 null
是一个合适的响应。但是Kotlin有null-safetly,所以要准确表示null
是可能的,Response<Void?>
是必须的,虽然稍微有点counter-intuitive.
如果库是纯 Kotlin,更好的设计是 Response<Nothing>
,当您调用 body()
.