在Kotlin中使用TypeAdapter实现TypeAdapterFactory

我正在尝试在我的android项目中使用Kotlin语言实现一些特定的GSON TypeAdapter。

我正面临的问题是编译错误,无法推断类型: 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的参数的原因不在此问题的上下文中。

这是不可能的,因为您覆盖的方法( TypeFactory.create )没有上限(在Kotlin中转换为<T : Any> )。 在你的create方法中, T不能保证是一个Enum<T> (所以,不可能把它作为参数传递给你的适配器)。

你可以做的只是删除你的适配器类的上限,并保持私有,以确保只有你的工厂可以创建它的实例(和工厂已经验证,如果类型是一个枚举)。

 class SmartEnumTypeAdapterFactory(fallbackKey: String) : TypeAdapterFactory { private val fallbackKey = fallbackKey.toLowerCase(Locale.US) override fun <T> create(gson: Gson?, type: TypeToken<T>): TypeAdapter<T>? { val rawType = type.rawType return if (!rawType.isEnum) null else SmartEnumTypeAdapter(rawType) } private class SmartEnumTypeAdapter<T>(classOfT: Class<in T>) : TypeAdapter<T>() { override fun write(out: JsonWriter?, value: T) { TODO("not implemented") } override fun read(`in`: JsonReader?): T { TODO("not implemented") } } } 

classOfTClass<in T>Class<in T>因为TypeToken.rawType()返回Class<? super T>