I'm writing a custom serializer for my custom class that extends the LinkedHashMap class. Here's the code:
@Serializable(with = ObservableLinkedHashMapSerializer::class)
class ObservableLinkedHashMap<K, V> : LinkedHashMap<K, V>() {
val mPublishSubject: PublishSubject<Boolean> = PublishSubject.create()
fun asObservable(): Observable<Boolean> {
return mPublishSubject
}
override fun putAll(from: Map<out K, V>) {
super.putAll(from)
mPublishSubject.onNext(true)
}
}
class ObservableLinkedHashMapSerializer<K, V> : KSerializer<ObservableLinkedHashMap<K, V>> {
override val descriptor: SerialDescriptor = PrimitiveSerialDescriptor("ObservableLinkedHashMap", PrimitiveKind.STRING)
override fun serialize(encoder: Encoder, value: ObservableLinkedHashMap<K, V>) {
val mapSerializer: KSerializer<LinkedHashMap<K, V>> = serializer()
mapSerializer.serialize(encoder, value)
}
override fun deserialize(decoder: Decoder): ObservableLinkedHashMap<K, V> {
val mapSerializer: KSerializer<LinkedHashMap<K, V>> = serializer()
return ObservableLinkedHashMap<K, V>().apply {
putAll(mapSerializer.deserialize(decoder))
}
}
}
It fails to compile and throws the error:
ObservableLinkedHashMap.java:6: error: incompatible types: Class<ObservableLinkedHashMapSerializer> cannot be converted to Class<? extends KSerializer<?>>
@kotlinx.serialization.Serializable(with = com.acme.app.ObservableLinkedHashMapSerializer.class)
Not sure why this happens, as I'm extending KSerializer as required and yet it fails.
Environment
This is a generic serializer, it has to take constructor parameters for K and V serializers. Btw. you don't need to have the @Serializer tag as you are not using any of the code generation of it.
What exact task of compilation fails? Given that file has for some reason .java extension, I suppose that this is a kapt task. Then it's maybe a #685
@sandwwraith Yes, this indeed fails in the kapt task. Is there a workaround I can use?
Most helpful comment
What exact task of compilation fails? Given that file has for some reason
.javaextension, I suppose that this is a kapt task. Then it's maybe a #685