Kotlinx.serialization: Why do I get incompatible types when I extend KSerializer in my custom serializer?

Created on 16 Oct 2020  路  3Comments  路  Source: Kotlin/kotlinx.serialization

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

  • Kotlin version: 1.4.10
  • Library version: 1.0.0
  • Kotlin platforms: JVM (using kotlin-android plugin)
  • Gradle version: 6.5
  • IDE version: Android Studio 4.1
bug compiler-plugin

Most helpful comment

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

All 3 comments

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?

Was this page helpful?
0 / 5 - 0 ratings