Updated 28 February 2022
In this blog, we going to discuss the Kotlin data classes.
Data is the main key source of any application we get the data from the different storage media like from the local storage or from the remote source.
For using the data received from storage media we use the classes on which we have created getter and setter to read and update that data as we do in java.
But Kotlin provides the support of data classes to store our data. So with the help of the data classes, we do not need to create our own getter and setter to use the data. Kotlin data classes provide the default implementation for the getter and setter functions.
Kotlin data classes also provide so extra functions for us as well which can be easily used to manipulate our data easily without adding the extra implementation for the same.
So basically data classes hold data and provide some function for the data use. With the normal class, we use the data keyword to declare the class as a data class.
1 |
data class Product(val productId: Int, val productName: String) |
There are some rules for creating the data classes:
The compiler will provide the below functions for the data classes:
It returns the value of the variable as a string. We can use this function like below:
1 2 3 4 |
val product=Product(109, "shirt") //To return the the value as string form use toString() product.toString() |
This is used to return the same copy of one object to another. If we want to use the copy of one object in another we can easily do this with the help of copy() like below:
1 2 3 4 5 6 7 |
val product = Product(109, "shirt") //To return the the same copy to other object use copy() val productTwo = product.copy() //If we want to make some chages on the value with copy() val productTwo = product.copy(productId = 110) |
It will return the hash code of the object. If equals() returns the true then the hash code of the both object are the same integer value. We can get the hash value like below:
1 2 3 4 5 |
val product = Product(109, "shirt") //get the hash value of the object in integer form like product.hashCode() |
This is used to compare two objects it returns the true value if the object have same value. We can compare the two object like below:
1 2 3 4 5 6 7 |
val product = Product(109, "shirt") val productTwo = product.copy() //if we compare the objects and values are same then it returns true product.equals(productTwo) |
In this blog, we have learned about the implementation of the Kotlin data classes.
For more information regarding the Kotlin data classes follow the link.
Thanks for reading this blog. You can also check other blogs from here.
If you have more details or questions, you can reply to the received confirmation email.
Back to Home
Be the first to comment.