How to use @Serializable as a interface?

Viewed 47

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?

1 Answers

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.

Related