Lukas Lechner
Lukas Lechner

Reputation: 8191

Kotlin data classes: Why does toString() export private properties

This Kotlin data class

data class PhoneNumber(val prefix: String, private val lineNumber: String)

has the private property lineNumber.

When I create an object:

val phoneNumber = PhoneNumber("0676", "123456")
// toString() = PhoneNumber(prefix=0676, lineNumber=123456)

I do not expect that the toString() function also exposes lineNumber.

In Effective Java, Joshua Bloch writes

Provide programmatic access to all of the information contained in the value returned by toString()

If you won't do this, clients of your library will parse the toString() result to get access to lineNumber.

Does anyone know why Kotlin does not hide private properties in toString() in data classes as a default?

Upvotes: 2

Views: 1642

Answers (1)

mfulton26
mfulton26

Reputation: 31234

I'm not sure why Kotlin allows private properties in data class constructors but it seems to me that for a data class, "a class to do nothing but hold data", you would want all of the data properties to be public and to be used in equals(), hashCode(), toString(), componentN() functions, and copy().

If this is not the case then I wouldn't call such a class a "data class" and equals(), hashCode(), etc. should be explicitly implemented.

Upvotes: 5

Related Questions