One nice 'feature' of `kotlinx.serialization` is t...
# serialization
d
One nice 'feature' of
kotlinx.serialization
is that, in many cases, we can use: • 👁️ JSON in Debug builds for observability, then almost effortlessly switch to... • CBOR for Production, to gain the time/space optimisation afforded by that format However; the
StringFormat
and
BinaryFormat
interfaces these conform to are disjoint - only the
SerialFormat
interface is common, with no common encode/decode functions. To some degree this is understandable - one works with Strings and the other Bytes, so we'd expect them to be optimised for each. But; there's surely an opportunity to make the switch a bit more seamless, something like this; but out-of-the-box:
Copy code
fun SerialFormat.encode(obj: Any): ByteArray = when (this) {
    is BinaryFormat -> encodeToByteArray(obj)
    is StringFormat -> encodeToString(obj).encodeToByteArray()
    else -> throw IllegalArgumentException("Unsupported format: $this")
}

inline fun <reified T:Any> SerialFormat.decode(byteArray: ByteArray): T = when (this) {
    is BinaryFormat -> decodeFromByteArray(byteArray)
    is StringFormat -> decodeFromString(byteArray.decodeToString())
    else -> throw IllegalArgumentException("Unsupported format: $this")
}
Thoughts?
👍 1
c
I don't like throwing runtime exceptions for stuff that should be checked at compile-time. You could create your own interface with the methods you want and create thin wrappers for
BinaryFormat
and
StringFormat
that implement it
d
Agreed Ivan; let me be clear; I'm not proposing this code as is. It just illustrates a need, I'm asking who sees value in a 'better equivalent' to this, out of the box.
👍 3
e
for that use case I'd use Cbor 100% of the time and pretty-print it for debug
then you won't run into issues of encoders that work with Json format and pass debug, but then fail in production