Junior — Middle
What is the purpose of the toString method in the Any class in Kotlin or other JVM languages?
sobes.tech AI
Answer from AI
The toString method in the Any class (equivalent to Object in Java) is responsible for converting an object into a string representation. In Kotlin and other JVM languages, it is often overridden for debugging and logging convenience to output informative information about the object's state.
By default, toString returns the class name and hash code, which is not always useful. Overriding it allows, for example, to display field values:
class User(val name: String, val age: Int) {
override fun toString(): String {
return "User(name=$name, age=$age)"
}
}
This simplifies reading logs and diagnostics during development.