1

I am working on a plugin type system where 3rd parties will register classes that will expose data. I don't know exactly what the data will look like but I will enumerate these plugin instances collect the data and I would like to serialise it. A simplified version.

interface DataProvider {
  fun getDataThatIsSerializable() : ???
}

What can i set the return type to so that I know that I will be able to serialise it with kotlinx serialisation. I cannot see any common interface that is injected into the class and given thet kotlin doesn't support type classes its not clear how to achieve what I am trying to do?

I considered something like this:

interface DataProvider {
  fun getDataThatIsSerializable() : Pair<Any,KSerializer<*>>
}

but i could not pass this into the Json.encodeAsString functions, the types do not match

Are there any other options I can consider?

Luke De Feo
  • 2,025
  • 3
  • 22
  • 40
  • Hi Luke, can you please provide a [Minimal, Reproducible Example](https://stackoverflow.com/help/minimal-reproducible-example)? This would make it much more easy to help you out. – yezper Sep 14 '22 at 08:39

1 Answers1

0

kotlinx.serialization doesn't like serializing things unless you can tell it exactly what you're working with.

Would it make sense for the DataProvider to be responsible for serializing its own data? Something like:

interface DataProvider {
    fun getDataThatIsSerializable() : Any
    fun encodeAsJsonString(data: Any) : String
}

@Serializable
data class Foo(val value: Int)

class FooDataProvider : DataProvider {
    override fun getDataThatIsSerializable() : Any {
        return Foo(7)
    }

    override fun encodeAsJsonString(data: Any): String {
        return Json.encodeToString(Foo.serializer(), data as Foo)
    }
}

dnault
  • 8,340
  • 1
  • 34
  • 53