在 Kotlin 中使用 TypeAdapter 实现 TypeAdapterFactory

Den*_*mus 5 android gson kotlin

我正在尝试用 Kotlin 语言为我的 android 项目实现一些特定的 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")
        }
     }
  }
Run Code Online (Sandbox Code Playgroud)

classOfT: Class<T>我想将TypeAdapter 作为参数的原因是脱离了这个问题的上下文。

Mar*_*aro 2

这是不可能的,因为您要覆盖的方法 ( TypeFactory.create) 没有上限(<T : Any>在 Kotlin 中翻译为)。在您的create方法中,T不保证是 a 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")
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

(classOfT是 aClass<in T>因为TypeToken.rawType()返回 a Class<? super T>)