Kotlin is a statically typed programming language that runs on the Java Virtual Machine. It is a general-purpose language that is designed to be concise, safe, and interoperable.
One of the features that makes Kotlin stand out is its support for data classes. A data class is a class that is designed to hold data. In Kotlin, data classes come with a lot of built-in functionality, including the ability to generate equals(), hashCode(), and toString() methods automatically.
In this post, we'll take a look at how to use data classes in Kotlin and how to automatically generate equals(), hashCode(), and toString() methods.
To create a data class, we use the keyword data:
data class User(val name: String, val age: Int)
This creates a data class with two properties: name and age. We can also create data classes with mutable properties:
data class User(var name: String, var age: Int)
Data classes can also have secondary constructors:
data class User(val name: String, val age: Int) {
constructor(name: String) : this(name, 0)
}
By default, data classes in Kotlin generate equals() and hashCode() methods. These methods compare the data in two data classes and return true if they are equal.
Here's an example of how the equals() method works:
val user1 = User("John", 30)
val user2 = User("John", 30)
println(user1 == user2) // true
In this example, we have two data classes with the same name and age properties. When we compare them using the == operator, the equals() method is called and returns true.
If we change one of the properties, the equals() method will return false:
val user1 = User("John", 30)
val user2 = User("John", 31)
println(user1 == user2) // false
Data classes in Kotlin also generate a toString() method. This method is used to convert the data in a data class to a string.
Here's an example of how the toString() method works:
val user = User("John", 30)
println(user.toString()) // User(name=John, age=30)
As you can see, the toString() method prints out the data in the data class in a readable format.
In this post, we looked at data classes in Kotlin and how to automatically generate equals(), hashCode(), and toString() methods. Data classes are a great way to create concise and safe code.