Effective Kotlin: Item 12 — Always override toString

In item 12 of Joshua Bloch’s remarkable book, Effective Java, he covers overriding toString. With Kotlin’s data class providing an implementation of toString you may think it unnecessary to write your own.

The toString produced in a data class lists each property in order of definition. The code below will produce the string “User(name=Bob, age=30)”:

data class User(val name: String, val age: Int)

println(User("Bob", 30))

Joshua says, “when practical, the toString method should return all of the interesting information contained in the object.” but that’s to say there are circumstances under which the string remains concise but informed. You want the output to contain enough valuable information but not too much. So just because a data class defines a toString doesn’t mean you shouldn’t override it.

Each week I am looking at “items” from Joshua Bloch’s well-respected book, Effective Java to see how it applies to Kotlin. You can find the rest of the items I’ve covered at Effective Kotlin. Please let me know your thoughts.

Matt Dolan has been eating doughnuts and developing with Android since the dark days of v1.6.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store