0

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
  • 1
    It's not entirely clear for me what you mean. Omit optional parameters when doing what exactly? When creating an object, when printing it in toString()? If the latter, how would you like to distinguish cases when cis null and b is null (assuming it is optional as well)? Both these cases would produce exactly same output. You can always implement toString() by yourself. Commented Aug 31, 2023 at 23:54

1 Answer 1

0

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.