generics - Kotlin将类转换为Unit

标签 generics kotlin

如何将通用类强制转换为Unit?

resultType is 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))
    }
}

关于generics - Kotlin将类转换为Unit,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62244846/

相关文章:

kotlin - 如何在 Kotlin 协程中使用阻塞(I/O 绑定(bind))API?

generics - 为什么 Rust 不使用默认的泛型参数类型

c# - 应用约束的通用错误

c# - 为什么受约束的返回类型需要显式转换?

generics - 为什么在具有泛型类型参数的结构定义中使用特征边界?

kotlin - 如果kotlin包具有多个主要功能,该如何调用特定功能?

C#:泛型语法问题

kotlin - 在 Kotlin 中扩展具有不同签名的 2 个 lambda

kotlin - Kotlin中*操作的作用是什么?

kotlin - 在表达式Kotlin中优化重复代码