Skip to content
DeveloperMemos

Overriding toString in Kotlin

Kotlin, Android Development1 min read

The toString() method is a commonly used method in object-oriented programming languages that provides a string representation of an object. By default, Kotlin's toString() method returns a string containing the class name and the object's hashcode. However, there are cases when you may want to customize the string representation of an object to provide more meaningful information. In this article, we will learn how to override the toString() method in Kotlin, specifically in the context of Android development.

Overriding toString()

To override the toString() method in Kotlin, you simply need to define a new implementation of the method within your class. The new implementation should return a string representation of the object according to your requirements.

Here's an example where we have a Person class representing a person's name and age:

1class Person(val name: String, val age: Int) {
2 override fun toString(): String {
3 return "Person(name=$name, age=$age)"
4 }
5}

In the above example, we override the toString() method and provide a custom string representation for a Person object. The returned string includes the values of the name and age properties.

Using toString()

Once you have overridden the toString() method, you can use it to obtain a string representation of an object. This can be useful for debugging, logging, or displaying information about an object in your Android application.

For example, let's assume we have a User class representing a user in our Android app:

1class User(val id: Int, val username: String) {
2 override fun toString(): String {
3 return "User(id=$id, username='$username')"
4 }
5}

In the above example, the toString() method is overridden to provide a formatted string representation of the User object, including the id and username properties.

Now, let's say we have an instance of the User class:

1val user = User(1, "john_doe")
2Log.d("TAG", user.toString()) // Output: User(id=1, username='john_doe')

By calling toString() on the user object, we obtain a string representation that includes the values of its properties. This can be helpful for debugging purposes or when you need to display user information in your app.

Summary

In this article, we explored how to override the toString() method in Kotlin. By providing a custom implementation of toString() within a class, you can define a more meaningful string representation for objects. We showcased examples in the context of Android development, where overriding toString() can be useful for debugging and displaying information.