BeginnersBook

  • Home
  • Java
    • Java OOPs
    • Java Collections
    • Java Examples
  • C
    • C Examples
  • C++
    • C++ Examples
  • DBMS
  • Computer Network
  • Python
    • Python Examples
  • More…
    • jQuery
    • Kotlin
    • WordPress
    • SEO
    • JSON
    • JSP
    • JSTL
    • Servlet
    • MongoDB
    • XML
    • Perl

Kotlin Data Class with examples

Last Updated: March 13, 2019 by Chaitanya Singh | Filed Under: Kotlin Tutorial

In Kotlin, you can create a data class to hold the data. The reason why would you want to mark a class as data is to let compiler know that you are creating this class for holding the data, compiler then creates several functions automatically for your data class which would be helpful in managing data. In this guide, we will learn data class and the functions that are automatically generated by compiler.

A data class Student:

data class Student(val stuName: String, val stuAge: Int)

Automatically generated functions for data class in Kotlin

For now I am just mentioning the name of the functions here, we will see each one of them with the help of examples.
1. equals()
2. hashCode()
3. toString()
4. copy()
5. componentN()

Kotlin Data Class Requirements

In order to mark a class as data, the class must fulfil certain requirements. The requirements are as follows:
1. The primary constructor of the data class must have at least one parameter. Also, the parameters are either marked val or var.
2. The class cannot be marked as open, abstract, sealed or inner.
3. The class can extend (inherit) other class and it can also implements other interfaces.

Kotlin Data Class Example

In the following example, we have a class Student, which we have marked as data class. Since we have declared this class as data, compiler has automatically generated several functions such as copy(), toString(), equals() etc. for this class, we will discuss these functions in next few examples.

data class Student(val name: String, val age: Int)

fun main(args: Array<String>) {
    val stu = Student("Chaitanya", 31)
    val stu2 = Student("Ajeet", 30)
    println("Student Name is: ${stu.name}")
    println("Student Age is:  ${stu.age}")
    println("Student Name is: ${stu2.name}")
    println("Student Age is:  ${stu2.age}")
}

Output:
Kotlin Data class

Data class hashCode() and equals() methods

If two objects are equal in kotlin then they have the same hash code which we can get using the hashCode() method.
The method equals() returns true or false. If the hashCode() of two objects are equal then equals() returns true else it returns false.

data class Student(val name: String, val age: Int)

fun main(args: Array<String>) {
    val stu = Student("Chaitanya", 31)
    val stu2 = Student("Chaitanya", 31)
    val stu3 = Student("Ajeet", 30)
    if (stu.equals(stu2) == true)
        println("stu is equal to stu2.")
    else
        println("stu is not equal to stu2.")

    if (stu.equals(stu3) == true)
        println("stu is equal to stu3.")
    else
        println("stu is not equal to stu3.")

    println("Hashcode of stu: ${stu.hashCode()}")
    println("Hashcode of stu2: ${stu2.hashCode()}")
    println("Hashcode of stu3: ${stu3.hashCode()}")
}

Output:
Kotlin hashcode and equals functions

Data class copy() method

By using copy() method in data class, we can copy few of the properties of other objects. Lets take an example. Here we have an object stu of Student class that contains the name, age and subject details of a Student “Steve” and we have created another object stu2 with the name “Lucy” and copying the age and subject details of object stu using the copy() method of data class.

data class Student(val name: String, val age: Int, val sub: String)

fun main(args: Array<String>) {
    val stu = Student("Steve", 26, "Math")

    // copying the age and subject from object stu
    val stu2 = stu.copy(name = "Lucy")

    println("stu: Name ${stu.name}, Age ${stu.age} & Subject ${stu.sub}")
    println("stu2: Name ${stu2.name}, Age ${stu2.age} & Subject ${stu2.sub}")
}

Output:
Kotlin data class copy method

Data class toString() method

The toString() method of data class returns the String representation of an object.

data class Student(val name: String, val age: Int, val sub: String)

fun main(args: Array<String>) {
    val stu = Student("Steve", 26, "Math")
    println(stu.toString())
}

Output:

Student(name=Steve, age=26, sub=Math)

Data class componentN() method

The componentN() method of data class destructure an object into a number of variables. In the following example we have an object stu of Student class and we are destructuring the object into number of variables using the componentN() method. The component1() method returns the value of the first property of the object, component2() returns the value of second property and so on.

data class Student(val name: String, val age: Int, val sub: String)

fun main(args: Array<String>) {
    val stu = Student("Steve", 26, "Math")
    val name = stu.component1()
    val age = stu.component2()
    val sub = stu.component3()
    println("Name is: $name")
    println("Age is: $age")
    println("SUbject is: $sub")
}

Output:
Kotlin data class componentN() method

❮ PreviousNext ❯

Top Related Articles:

  1. Kotlin Class and Objects – Object Oriented Programming (OOP)
  2. Kotlin Keywords, Soft Keywords and Identifiers
  3. Kotlin Constructors with examples
  4. Kotlin Operators – Arithmetic, Assignment, Unary, Logical and More
  5. Kotlin Interfaces with examples

About the Author

I have 15 years of experience in the IT industry, working with renowned multinational corporations. Additionally, I have dedicated over a decade to teaching, allowing me to refine my skills in delivering information in a simple and easily understandable manner.

– Chaitanya

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

Kotlin Tutorial

  • Kotlin Tutorial
  • Kotlin in Eclipse IDE
  • Kotlin in IntelliJ
  • First Kotlin Program
  • Kotlin Keywords
  • Kotlin Variables
  • Kotlin Type Casting
  • Kotlin operators
  • Kotlin Input/Output
  • Kotlin Comments

Kotlin String

  • Kotlin String

Kotlin Array

  • Kotlin Array
  • Kotlin Range

Control Flow

  • Kotlin if expression
  • Kotlin when expression
  • Kotlin for loop
  • Kotlin while loop
  • Kotlin do-while loop
  • Kotlin continue
  • Kotlin break

Kotlin Function

  • Kotlin Function
  • Kotlin Recursion
  • Kotlin default and named arguments
  • Lambda functions
  • Higher Order Function

Exception Handling

  • Exception Handling
  • Kotlin try catch
  • Multiple catch blocks
  • Nested try catch
  • Throw keyword
  • Kotlin try expression

Kotlin OOP

  • Class and Objects
  • Kotlin Constructors
  • Kotlin Inheritance
  • Visibility Modifiers
  • Kotlin abstract class
  • Kotlin Interfaces
  • Nested and Inner Class
  • Kotlin Data Class
  • Kotlin Sealed Class

Copyright © 2012 – 2025 BeginnersBook . Privacy Policy . Sitemap