Thread
#jackson-kotlin
    s

    Sam

    2 months ago
    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
    data class MyClass(val s: String? = "some-default")
    I would like the following behaviour:
    val mc = MyClass() // MyClass(s = "some-default")
    but I also want:
    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

    2 months ago
    data class MyClassJacksonDelegate(val s: String? = null)
    data class MyClass(val s: String? = "some-default") {
        @JsonCreator
        constructor(delegate: MyClassJacksonDelegate) : this(delegate.s)
    s

    Sam

    2 months ago
    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!