我正在为我的android项目尝试在Kotlin语言中实现一些特定的GSON TypeAdapter。在Kotlin中使用TypeAdapter实现TypeAdapterFactory
我现在面临的问题是编译误差不能推断类型:Type inference failed: 'T' cannot capture 'in (T..T?'. Type parameter has an upper bound 'Enum<T>' that cannot be satisfied capturing 'in' projection
的代码如下:
class SmartEnumTypeAdapterFactory(fallbackKey: String) : TypeAdapterFactory {
private val fallbackKey = fallbackKey.toLowerCase(Locale.US)
override fun <T : Any> create(gson: Gson?, type: TypeToken<T>): TypeAdapter<T>? {
val rawType = type.rawType
return if (!rawType.isEnum) null else SmartEnumTypeAdapter(rawType)
}
class SmartEnumTypeAdapter<T : Enum<T>>(classOfT: Class<T>) : TypeAdapter<T>() {
override fun write(out: JsonWriter?, value: T) {
TODO("not implemented")
}
override fun read(`in`: JsonReader?): T {
TODO("not implemented")
}
}
}
我想有classOfT: Class<T>
作为参数TypeAdapter的原因是出这个问题的背景。
这是一个真正棘手的情况下......您是否尝试过用Java实现这个东西?因为那时你可以转换为Kotlin,看看它是否有效,但到目前为止,我还没有得到这两种语言的工作。 – Robin