In Kotlin, data classes offer a convenient way to handle classes only made to handle data. These types of data classes are called Data-centric classes. In this tutorial, we will learn about, What a data class is, how to declare a data class, and how to use a data class in Kotlin.
Kotlin Data Classes: A Complete Guide with Practical Examples
What is a Data class?
A data class in Kotlin is a special type of class that is designed to hold data only. Kotlin made it easy by providing a getter setter and removing all boilerplate code. To declare a data class we have to use the data keyword on class name declaration time.
Key features of Data Class:
- Automatically generates common functions and reduces our code.
- These functions are automatically generated toString(), equals(), hashCode(), copy(), and component functions.
- Support getter & setter without declaring.
Syntax of Data Class in Kotlin:
To define a data class we have to use the data class keyword.
1 2 3 |
// Data Class data class ClassName(val property1: Type, val property2: Type, ...) |
Example of creating a Data class in Kotlin:
For this example, we are creating a data class to store Student information. This class has 3 properties name, age, and email.
1 2 |
// Data Class data class Student(val name: String, val age: Int, val email: String) |
Creating object and get data class properties without Getter:
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 |
// Data Class data class Student(val name: String, val age: Int, val email: String) // Usage fun main() { println(studentObject) // Printing single property without Getter println(studentObject.name) println(studentObject.age) println(studentObject.email) } // Output // Student(name=Sam, age=17, [email protected]) // Sam // 17 |
Code explanation:
I have created a Student data class to store student name, age, and email. To retrieve the data from the student object there is no need to call the getter instead we can directly get the property value.
Creating objects and set data class properties without a Setter:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
// Data Class data class Student(var name: String, var age: Int, var email: String) fun main() { // Directly update properties studentObject.name = "John" studentObject.age = 18 } // Output // Student(name=John, age=18, [email protected]) |
In a data class to assign values to a single property there is no need to use a setter.
Conclusion:
Data classes make our code clean and short without disrupting the functionality. So when creating classes to store data then always use data classes. Keep practicing and you will master the data classes in Kotlin.