https://kotlinlang.org logo
s

Sam

07/13/2022, 8:11 AM
I'd like to have a data class parameter that gets a default value when creating a new instance from code but not when deserialising. What's the simplest way to do that? I'll add examples in the thread.
e.g. given the class
Copy code
data class MyClass(val s: String? = "some-default")
I would like the following behaviour:
Copy code
val mc = MyClass() // MyClass(s = "some-default")
but I also want:
Copy code
mapper.readValue<MyClass>("{}") // MyClass(s = null)
The best approach I can think of so far basically involves having two separate constructors. And even that isn't very easy because depending on the use case the two constructors can end up with the same signature (just different defaults). Is there a way to do it with a single constructor, for example with an annotation on the property?
e

ephemient

07/13/2022, 11:47 PM
Copy code
data class MyClassJacksonDelegate(val s: String? = null)
data class MyClass(val s: String? = "some-default") {
    @JsonCreator
    constructor(delegate: MyClassJacksonDelegate) : this(delegate.s)
👌 1
s

Sam

07/14/2022, 7:46 AM
That’s very neat 👍. A bit of effort to set up, since it means declaring two versions of the class, but once that’s done, it does exactly what I was asking for. Very clean from the point of view of anyone using the class.
Thanks!
6 Views