gpt4 book ai didi

generics - Kotlin将类转换为Unit

转载 作者:行者123 更新时间:2023-12-02 13:29:36 25 4
gpt4 key购买 nike

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

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com