I'm getting this error `Class 'ClassOutsideOfLibra...
# serialization
j
I'm getting this error
Class 'ClassOutsideOfLibrary' is not registered for polymorphic serialization in the scope of 'MyInterface'.
Is it any way possible to have an interface in my library and then have users of my library implementing this interface and then passing objects into my functions, where I then call
encodeToString
on this object they provided?
Found a solution.
Copy code
polymorphicDefaultSerializer(MyInterface::class) { obj: MyInterface ->
    object: SerializationStrategy<MyInterface> {
      override val descriptor = buildClassSerialDescriptor("test") {
        deliverable::class.memberProperties.forEach { field ->
          element<String>(field.name, field.annotations)
        }
      }

      override fun serialize(encoder: Encoder, value: MyInterface) {
        encoder.encodeStructure(descriptor) {
          obj::class.memberProperties.forEachIndexed { index, field ->
            when (field.returnType.toString()) {
              "kotlin.String" -> {
                val v = (field as KProperty1<MyInterface, String>).get(obj)
                encodeStringElement(descriptor, index, v)
              }
              "<http://kotlin.Int|kotlin.Int>" -> {
                val v = (field as KProperty1<MyInterface, Int>).get(obj)
                encodeIntElement(descriptor, index, v)
              }
              "kotlin.Boolean" -> {
                val v = (field as KProperty1<MyInterface, Boolean>).get(obj)
                encodeBooleanElement(descriptor, index, v)
              }
              // etc.
              else -> throw DataException("It's currently not possible to encode data of type '${field.returnType}'")
            }
          }
        }
      }
    }
}