How to default null values on a data class?

I have the following class with a default value for the property name.

data class Location constructor(
    val lat: Double,
    val lon: Double,
    val name: String = ""

Fine. If I call the constructor without passing a value for name, it initializes properly with the empty string but…

Not fine, it gets called with the argument null by a deserialization framework (and maybe other frameworks).

If I make the constructor parameter nullable and not a val, I can’t make it a data class so I lose hashCode, toString, copy, etc.

If I add a secondary constructor and fix up the arguments, that’s also no bueno because the serialization framework will call the primary constructor if I change parameter names. I’m refactoring from Java so I am somewhat limited but the deserialization is bound to external integrations so that’s an even bigger limitation.


Why do you think so? Kotlin Playground: Edit, Run, Share Kotlin Code Online

I haven’t used too many serialization libraries, but Jackson has an official plugin for Kotlin and calls construtor with default arguments when absent in input JSON. Another one is kotlinx.serialization which has this out of the box.

Not make it a var but a bare parameter.