首页 > 解决方案 > 在 Kotlin 中检查 isAssignableFrom 后如何转换泛型类型?

问题描述

请参阅示例:


class MyTypeAdapter<T : Throwable>
    (private val gson: Gson, private val skipPast: TypeAdapterFactory) : TypeAdapter<T>() {
   // :Throwable is needed to access the stackTrace field
}

private class ThrowableTypeAdapterFactory : TypeAdapterFactory {
    override fun <T> create(gson: Gson, typeToken: TypeToken<T>): TypeAdapter<T>? {
        if (Throwable::class.java.isAssignableFrom(typeToken.rawType)) {
            return MyTypeAdapter<T>(gson, this) // compile error: Type argument is not within its bound
        }
        return null
    }
}

所以在 Java 中我们有原始使用参数化类,但 Kotlin 不再允许它了。我试图从https://kotlinlang.org/docs/reference/generics.html中找到一些东西, 但找不到线索。请指教。

标签: kotlingenerics

解决方案


由于类型擦除,您应该能够作弊:

return MyTypeAdapter<Throwable>(gson, this) as MyTypeAdapter<T>

看起来不对,但是类实际上不能根据T.

或者如果 Kotlin 不会直接接受这个演员表(目前无法检查),比如

return (MyTypeAdapter<Throwable>(gson, this) as MyTypeAdapter<*>) as MyTypeAdapter<T>

甚至

return (MyTypeAdapter<Throwable>(gson, this) as Any) as MyTypeAdapter<T>

应该管用。


推荐阅读