如何将通用类强制转换为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/

10-09 17:22