在Kotlin中使用TypeAdapter实现TypeAdapterFactory

时间:2017-10-17 16:15:15

标签: 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")
        }
     }
  }

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

1 个答案:

答案 0 :(得分:0)

这是不可能的,因为您覆盖的方法(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>因为TypeToken.rawType()返回Class<? super T>