Support default values
aafanasev opened this issue · comments
data class Entity(val id: Int = 42)
Progress?
@dri94 WIP
when doing it, will the ability for values in json that come down as null be mapped to default values too?
Hello, @aafanasev
Can we provide an annotation, suppose it is called @Default
, and the function annotated by it can provide the default value of this data class?
For example, for this data class:
data class Foo(
@SerializedName("str")
val stringValue: String,
@SerializedName("integer")
val intValue: Int
) {
companion object {
@Default
fun provideDefault(): Foo = Foo("string value", 233)
}
}
or data class with default value:
data class Bar(
@SerializedName("str")
val stringValue: String = "default",
@SerializedName("integer") = 233
val intValue: Int
) {
companion object {
@Default
fun provideDefault(): Bar {
return Bar()
}
}
}
And then, the generated class's deserialize function will look like this:
override fun read(reader: JsonReader): Foo? {
if (reader.peek() == JsonToken.NULL) {
reader.nextNull()
return null
}
// Foo.provideDefault() is annotated by @Default
val default = Foo.provideDefault()
var stringValue: kotlin.String? = null
var intValue: kotlin.Int? = null
reader.beginObject()
while (reader.hasNext()) {
if (reader.peek() == JsonToken.NULL) {
reader.nextNull()
continue
}
when (reader.nextName()) {
"str" -> stringValue = string_adapter.read(reader)
"integer" -> intValue = int_adapter.read(reader)
else -> reader.skipValue()
}
}
reader.endObject()
return Foo(
stringValue = stringValue ?: default.stringValue,
intValue = intValue ?: default.intValue
)
}
From the point of caller, this way just add an optional annotation, I think it just ok.
@zkw012300 awesome! I'll prepare a POC of your solution.