In this tutorial you will learn about the Kotlin Data Class and its application with practical example.
Kotlin Data Class
The class which is declared as “data” known as data class. All data classes must have at least one primary constructor and primary constructor should have at least one parameter. It can not be open, abstract, inner and sealed. Data class can extend other classes also can implement interface. It have some inbuilt function like “toString()” ,”hashCode(),equals() ,copy() etc. and we can use them.
Example: Let’s get understand it by an example. See below code.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 |
data class Article(val name: String, val publisher: String, var reviewCount: Int) fun main(args: Array<String>) { val article: Article = Article("Kotlin Tutorial", "W3adda.com", 8) println("W3Adda : Name of the Article is :-" + article.name) // "Kotlin Tutorial" println("W3Adda : Publisher Name :-" + article.publisher) // "W3adda.com" println("W3Adda : Review of the article is :-" + article.reviewCount) // 8 article.reviewCount = 9 //using "toString()" inbuilt function of the data class println("W3Adda : Printing all the information :-" + article.toString()) //using "hashCode()" inbuilt function of the data class println("Example of the HashCode function :-" + article.hashCode()) //using "copy()" inbuilt function of data class val c2 = article.copy(name = "Java") //copying val c3 = c2.copy() //using "equals()" inbuilt function of data class if (c2.equals(c3)) println("c3 is equal to c2") println("c2: name = ${c2.name}, publisher = ${c2.publisher}, reviewCount=${c2.reviewCount}") } |
Here, I have used some inbuilt function which are created by the compiler, when we declared class as “data” class. Let’s understand inbuilt function one by one
toString(): This function is used to returns a string representation of the object. Check below code which is used in above example.
1 2 |
//using "toString()" inbuilt function of the data class println("W3Adda : Printing all the information :-" + article.toString()) |
hashCode(): This function is used to returns hash code of the object. Check below lines which is used in above example for printing hashCode of object.
1 2 3 |
//using "hashCode()" inbuilt function of the data class println("Example of the HashCode function :-" + article.hashCode()) |
Copy(): This function is used to create a copy of an object with some of its properties and also can copy whole object. Check below lines.
1 2 3 |
//using "copy()" inbuilt function of data class val c2 = article.copy(name = "Java") //copying val c3 = c2.copy() |
Equals(): This function is used to check whether objects are equals. Check below lines.
1 2 3 4 |
if (c2.equals(c3)) println("c3 is equal to c2") else println("c3 is not equal to c2") |
Output: Let’s run this code you will get output like below image.