Android 在Kotlin中使用TypeAdapter实现TypeAdapterFactory
我正在尝试用Kotlin语言为我的android项目实现一些特定的GSON类型适配器 我面临的问题是无法推断类型的编译错误:Android 在Kotlin中使用TypeAdapter实现TypeAdapterFactory,android,gson,kotlin,Android,Gson,Kotlin,我正在尝试用Kotlin语言为我的android项目实现一些特定的GSON类型适配器 我面临的问题是无法推断类型的编译错误:类型推断失败:'T'cannotcapture'in(T..T?')。类型参数有一个上限'Enum',无法满足捕获'in'projection 代码如下: class SmartEnumTypeAdapterFactory(fallbackKey: String) : TypeAdapterFactory { private val fallbackKey
类型推断失败:'T'cannotcapture'in(T..T?')。类型参数有一个上限'Enum',无法满足捕获'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")
}
}
}
class SmartEnumTypeAdapterFactory(回退键:字符串):TypeAdapterFactory{
private val fallbackKey=fallbackKey.toLowerCase(Locale.US)
重写趣味创建(gson:gson?,类型:TypeToken):TypeAdapter{
val rawType=type.rawType
如果(!rawType.isEnum)为null,则返回其他SmartNumTypeAdapter(rawType)
}
类SmartEnumTypeAdapter(classOfT:class):类型适配器(){
重写有趣的写入(输出:JsonWriter?,值:T){
待办事项(“未实施”)
}
重写趣味阅读(`in`:JsonReader?):T{
待办事项(“未实施”)
}
}
}
我希望将
classOfT:Class
作为TypeAdapter的参数的原因与此问题无关。这是不可能的,因为您正在覆盖的方法(TypeFactory.create
)没有上限(在Kotlin中转换为
)。在create
方法中,T
不可用
保证为Enum
(因此,不可能将其作为参数传递给适配器)
您可以做的只是删除适配器类中的上限,并将其保持为私有,以确保只有您的工厂可以创建它的实例(如果类型是枚举,工厂已经验证)
class SmartEnumTypeAdapterFactory(回退键:字符串):TypeAdapterFactory{
private val fallbackKey=fallbackKey.toLowerCase(Locale.US)
重写趣味创建(gson:gson?,类型:TypeToken):TypeAdapter{
val rawType=type.rawType
如果(!rawType.isEnum)为null,则返回其他SmartNumTypeAdapter(rawType)
}
私有类SmartEnumTypeAdapter(classOfT:class):TypeAdapter(){
重写有趣的写入(输出:JsonWriter?,值:T){
待办事项(“未实施”)
}
重写趣味阅读(`in`:JsonReader?):T{
待办事项(“未实施”)
}
}
}
(
classOfT
是一个Class
,因为TypeToken.rawType()
返回一个Class这是一个非常棘手的问题……你有没有试过用Java实现这个问题?因为这样你就可以转换成Kotlin,看看它是否有效,但到目前为止,这两种语言都无法实现。
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")
}
}
}