Justin
06/09/2020, 6:36 PMAny
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:
@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:
interface StoredValue {
val type: String
val value: JsonElement // This would become of type Value
}
@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.Big Chungus
06/14/2020, 3:04 PMBig Chungus
06/14/2020, 3:04 PMBig Chungus
06/14/2020, 3:06 PMinterface 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