Omit optional parameters set as null in Kotlin data class

169 Views Asked by At

Best practice to omit optional parameter in a data class when its assigned null?

Example: data class xyz(val a:String ?,val b: String?, val c: String?= null) if c = null, then data class xyz(val a:String ?,val b: String?).

Calling xyz.toString() which takes null as "null". So output is xyz("String for a", String for b", "null").

But actual output xyz("String for a", String for b").

Can I use secondary constructor or invoke() ? Which is better?

1

There are 1 best solutions below

0
ryankuck On

If you sometimes need a value c but not in this case, then the two options are:

val newXyzObject = xyz(a = "String for a", b = "String for b", c = null)

or

val newXyzObject = xyz(a = "String for a", b = "String for b")

but since c has a default value it is preferred to go with the second option because it is more readable.