When the sole responsibility of the class is to hold some data, the data should be in presentable form. A data class provides the toString() function to display well-formatted class properties. Let's have a look at an example:
- Create a Person data class:
data class Person(var name : String, var age: Int, var height: Double)
- Display all properties using string interpolation or concatenation:
println("Name ${person.name}, Age ${person.age} Height ${person.height}")
- Call the toString() function using the person object as a reference, person.toString().
- The toString() function converts the object into a string representation.
Check the following example:
ClassName (property=value)
fun main(args: Array<String>) {
val person = Person("Abid", 40, 6.0)
println("Name ${person.name}, Age ${person.age} Height ${person.height}")
println(person.toString())
}
Take a look at the output; the toString() function combines each property along with its value in string-representation format:
The benefit of the toString() function is that Kotlin will automatically update the toString function if we add a new property or remove the existing one:
data class Person(var name :String, var age :Int, var country :String)
println(person.toString())
The toString() function can either be called explicitly, by using the println(person.toString()) object, or it can be called automatically, by passing the object to the print function, println(person).