Kotlin 将泛型类转换为 Unit



如何将泛型类转换为 Unit?

结果类型为单位

private fun <R : Any> Deferrable<R>.resolve(result: String?, resultType: Class<R>) {
when  {
resultType is Unit -> send(Unit)
null -> throw NullPointerException("result is expected to be of type ${resultType}")
else -> send(Json.parse(result, resultType))
}
}

所以,我找到了解决方案

@Suppress("UNCHECKED_CAST")
private fun <R : Any> Deferrable<R>.resolve(result: String?, resultType: Class<R>) {
when {
resultType.isInstance(Unit) -> send(Unit as R)
result == null -> throw NullPointerException("result is expected to be of type $resultType")
else -> send(Json.parse(result, resultType))
}
}

我不知道是否可以投射它,但你可以这样做:

private fun <R : Any> Deferrable<R>.resolve(result: String?, resultType: Any?) {
when (resultType)  {
is Unit -> send(Unit)
null -> throw NullPointerException("result is expected to be of type ${resultType}")
else -> send(Json.parse(result, resultType))
}
}

编辑:当我发布它时,我还没有看到你的答案,但也许它可以提供帮助。

最新更新