Deploying TypeAdapterFactory with TypeAdapter in Kotlin

I am trying to implement some specific type of GSON adapter in the Kotlin language for my Android project.

The problem I encountered is a compilation error with the inability to infer the type: Type inference failed: 'T' cannot capture 'in (T..T?'. Type parameter has an upper bound 'Enum<T>' that cannot be satisfied capturing 'in' projection

The following code:

  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")
        }
     }
  }

The reason I want to have classOfT: Class<T>a TypeAdapter as a parameter is outside the context of this problem.

+4
source share
1 answer

This is not possible, because the method you are rewriting ( TypeFactory.create) does not have an upper bound (which translates <T : Any>to Kotlin). There is create Tno guarantee in your method Enum<T>(therefore, it cannot be passed as an argument to your adapter).

, , , factory ( factory , ).

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")
        }
    }
}

(classOfT Class<in T>, TypeToken.rawType() a Class<? super T>)

0

Source: https://habr.com/ru/post/1687661/


All Articles