CodeBlanks Logo Icon CodeBlanks

toString

Learn automatic toString generation.

Automatic toString generation

Data classes generate the toString method automatically. It produces a readable form with the class name and property values.

Example: data class Book(val title: String, val author: String). Calling println(Book("Kotlin", "JetBrains")) outputs Book(title=Kotlin, author=JetBrains). In normal classes without an override, toString prints a memory address; data classes avoid this. It is ideal for debugging and logging.

The toString format

The toString format of data classes is ClassName(prop1=value1, prop2=value2). Property names and values are connected with =.

Example: data class Money(val amount: Double, val currency: String). Money(100.0, "USD").toString() returns Money(amount=100.0, currency=USD). Because println calls toString automatically, println(m) and println(m.toString()) produce the same output.

Practice toString with the Book data class

Define a data class named Book with a primary constructor taking val title: String, val author: String. In main create a Book("Kotlin", "JetBrains") instance. First print the result of b.toString(), then print b directly with println.

Starter code

Main.kt
// Define the Book data class
// with title and author properties
// instantiate in main
// print toString and the instance directly

Sample solution

Main.kt
data class Book(val title: String, val author: String)

fun main() {
    val b = Book("Kotlin", "JetBrains")
    println(b.toString())
    println(b)
}

Expected output

Book(title=Kotlin, author=JetBrains)
Book(title=Kotlin, author=JetBrains)

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Complete the toString call

Question
data class Book(val title: String, val author: String)
val b = Book("Kotlin", "JetBrains")
println(b.____())
Answer
data class Book(val title: String, val author: String)
val b = Book("Kotlin", "JetBrains")
println(b.toString())

Explanation: toString returns the readable string of the instance.

2 Match the toString parts

Term Meaning
Book Class name
title=Kotlin Property and value
, Separator
println(b) Automatic toString

3 <code>data class Book(val title: String, val author: String)</code> is defined. What does <code>println(Book("Kotlin", "JetBrains"))</code> print?

  • Book(title=Kotlin, author=JetBrains) Correct answer
  • Book@1a2b3c
  • Kotlin - JetBrains
  • Book

Explanation: A data class toString shows the class name and property-value pairs.

All lessons in Intermediate