1

I would like to write an function, that would work on any object which is serializable. Something like this:

inline fun <reified @Serializable T> T.serialiseToJson(): String {
    return format.encodeToString(this)
}

This doesnt work because you cant use @Serializable to annotate type parameter.

Is there a way to do this?

shaktiman_droid
  • 2,368
  • 1
  • 17
  • 32
beretis
  • 899
  • 1
  • 9
  • 24
  • Since it's not directly possible, have you thought about having an empty interface for all your serializable classes and then write a `reified` function as in your question with that interface type? With that, you can still use `encodeToString(this)` extension function and be sure that it won't throw unless there is a mismatch – shaktiman_droid Sep 04 '22 at 23:33
  • @shaktiman_droid yes, thats what I ended up doing. I'm pretty surprised that they don't have such a interface in the library. They rely solely on an anotations. – beretis Sep 06 '22 at 22:19

1 Answers1

1

A common way to handle this is to take a serializer as a parameter.

fun <T> T.serializeToJson(serializer: KSerializer<T>): String {
    return format.encodeToString(serializer, this)
}

It's a bit more verbose, but it's also more flexible because it allows the user to pass a custom serializer instead of always picking the generated one. And you have the same type-safety because you can only use it with types for which a KSerializer exists.

RussHWolf
  • 3,555
  • 1
  • 19
  • 26
  • The thing is, I would like to introduce this functionality on a data types that supports Serializable contract. Your function, if im not mistaken, can be called on any data type, you need to provide serializer though. I'm surprised that the library doesn't expose such a interface. – beretis Sep 06 '22 at 22:22