liveBook · Manning

ToString

As explained in Kotlin in Action, 2E

toString is an object method that returns a textual representation of the object.

toString returns a textual representation of an object. Kotlin classes provide it by default, but the default output, such as Customer@5e9f23b4, is mainly useful for identifying the class and is poor for debugging or logging. Override it to produce meaningful field values. section 4.3.1

Readable customer output

class Customer(val name: String, val postalCode: Int) { override fun toString() = "Customer(name=$name, postalCode=$postalCode)" } fun main() { val customer = Customer("Alice", 342562) println(customer) // Customer(name=Alice, postalCode=342562) } The override supplies a compact, informative representation; println uses it when displaying the object.

How Kotlin in Action, 2E covers it

How deep it goes
Explains the default output and demonstrates overriding toString, but does not detail generated implementations or deeper runtime mechanics.
Examples
Demonstrates a Customer class whose name and postalCode appear in println output.
What it assumes
Assumes basic Kotlin classes and properties while teaching the object-method override from a simple Customer declaration.
What you can do after
Apply it via an override that makes Kotlin objects more informative when printed, logged, or inspected during debugging.
How it connects
Connects to object methods, debugging, logging, and Java conventions for obtaining string representations.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Kotlin in Action, 2E. The section links point to the parts of the book it draws on.