我在 kotlin 中創建了帶有泛型的類,并希望使用帶有泛型的接收,但是當我想call.recieve從泛型輸入時出現錯誤:
Can not use MType as reified type parameter. Use a class instead.
代碼:
class APIRoute<EType : IntEntity, MType : Any> {
fun Route.apiRoute() {
post {
val m = call.receive<MType>()
call.respond(f(model))
}
}
}
如何解決?
uj5u.com熱心網友回復:
您需要為receive()函式提供預期的型別。由于Java/Kotlin 中的型別擦除, 的型別MType在運行時未知,因此不能與receive(). 您需要捕獲型別KType或KClass施工時的物件APIRoute。
KClass更易于使用,但它僅適用于原始類,不支持引數化型別。因此,我們可以使用它來創建 eg APIRoute<*, String>,但不能使用它APIRoute<*, List<String>>。KType支持任何型別,但有點難以處理。
解決方案KClass:
fun main() {
val route = APIRoute<IntEntity, String>(String::class)
}
class APIRoute<EType : IntEntity, MType : Any>(
private val mClass: KClass<MType>
) {
fun Route.apiRoute() {
post {
val m = call.receive(mClass)
call.respond(f(model))
}
}
}
解決方案KType:
fun main() {
val route = APIRoute.create<IntEntity, List<String>>()
}
class APIRoute<EType : IntEntity, MType : Any> @PublishedApi internal constructor(
private val mType: KType
) {
companion object {
@OptIn(ExperimentalStdlibApi::class)
inline fun <EType : IntEntity, reified MType : Any> create(): APIRoute<EType, MType> = APIRoute(typeOf<MType>())
}
fun Route.apiRoute() {
post {
val m = call.receive<MType>(mType)
call.respond(f(model))
}
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/363413.html
