What is the suggested approach for declaring a typ...
# serialization
j
What is the suggested approach for declaring a type that is basically
Any
but constrained to
String | Boolean | Int | Array | Map
, and then make that type serializable? Because there are no true union types in Kotlin, what I tried to do is this:
Copy code
@Serializable
sealed class Value<out T>(val value: T) {
    class STRING(value: String): Value<String>(value)
    class BOOLEAN(value: Boolean): Value<Boolean>(value)
    class NUMBER(value: Number): Value<Number>(value)
    class ARRAY<V>(value: List<V>): Value<List<V>>(value)
    class DICTIONARY(value: Map<String, Any?>): Value<Map<String, Any?>>(value)
    object NULL: Value<Nothing?>(null)
}
Then, I have a number of data classes/interfaces that need to use this type, for example:
Copy code
interface StoredValue {
    val type: String
    val value: JsonElement // This would become of type Value
}
Copy code
@Serializable
data class NetworkRequest(
    val type: String,
    val data: JsonElement // This would become of type Value
)
But if I try to use
Value
in place of
JsonElement
, then I need to attach the generic type parameter to those classes/interfaces, and then I'm not sure how to deal with serialization on them.
b
create marker interface and wrapper objects for those types that has value as prop and extend marker interface
That's what dukat is doing
e.g.
Copy code
interface StringOrNumber
inline class MyString(val value:String):StringOrNumber
inline class MyNumber(val value:Number):StringOrNumber
Inline classes are great for that as well as compiler unboxes them when spitting out bytecode