Kotlin – Data Class

Data class is a simple class which is used to hold data/state and contains standard functionality. A data keyword is used to declare a class as a data class.

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

Declaring a data class must contains at least one primary constructor with property argument (val or var).Data class internally contains the following functions:

  • equals(): Boolean
  • hashCode(): Int
  • toString(): String
  • component() functions corresponding to the properties
  • copy()

Due to presence of above functions internally in data class, the data class eliminates the boilerplate code.

Java data class VS Kotlin data class

If we want to create a User entry in Java using data class, it require lots of boilerplate code.

import java.util.Objects;

public class User {
    private String name;
    private int id;
    private String email;

    public User(String name, int id, String email) {
        this.name = name;
        this.id = id;
        this.email = email;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public intgetId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (!(o instanceof User)) return false;
        User user = (User) o;
        return getId() == user.getId() &&
                Objects.equals(getName(), user.getName()) &&
                Objects.equals(getEmail(), user.getEmail());
    }

    @Override
    public inthashCode() {

        return Objects.hash(getName(), getId(), getEmail());
    }

    @Override
    public String toString() {
        return "User{" +
                "name='" + name + '\'' +
                ", id=" + id +
                ", email='" + email + '\'' +
                '}';
    }
}

Calling the constructor of above Java data class using the object of User class as

class MyClass{
    public static void main(String agrs[]){
        User u = new User("Ashu",101,"mymail@mail.com");
        System.out.println(u);
    }
}

Output :

User{name='Ashu', id=101, email='mymail@mail.com'}

The above Java data class code is rewritten in Kotlin data code in single line as

data class User(var name: String, var id: Int, var email: String)

Calling the constructor of above Kotlin data class using the object of User class as

fun main(agrs: Array<String>) {
    val u = User("Ashu", 101, "mymail@mail.com")
    println(u)
}

Output :

User(name=Ashu, id=101, email=mymail@mail.com)

Requirements of data class

In order to create a data class, we need to fulfill the following requirements:

  • Contain primary constructor with at least one parameter.
  • Parameters of primary constructor marked as val or var.
  • Data class cannot be abstract, inner, open or sealed.
  • Before 1.1,data class may only implements interface. After that data classes may extend other classes.

1. data class toString() methods

Kotlin data class only focuses on data rather than code implementation.  Let’s see a simple program without data class. In this class, we are trying to print the reference of Product class using its object

class Product(varitem: String, var price: Int)
fun main(agrs: Array<String>) {
    val p = Product("laptop", 25000)
    println(p)
}

While printing the reference of Product class, it displays the hashCode() with class name of Product. It does not print the data.Output :

Product@266474c2

The above program is rewritten using data class and printing the reference of Product class and displaying the data of object. It happens because the data class internally contains the toString() which display the string representation of object .

data class Product(varitem: String, var price: Int)
fun main(agrs: Array<String>) {
    val p = Product("laptop", 25000)
    println(p)
}

Output :

Product(name=laptop, price=25000)

2. data classequals() and hashCode()

The equal() method is used to check other object is “equal to” current object. While doing comparison between two or more hashCode(), equals() method returns true if the hashCode() are equal, else it returns a false.For example, let’s see an example in which a normal class comparing the two references of same class Product having same data.

class Product(varitem: String, var price: Int)
fun main(agrs: Array<String>) {
    val p1 = Product("laptop", 25000)
    val p2 = Product("laptop", 25000)
    println(p1==p2)
    println(p1.equals(p2))
}

In above program, reference p1 and reference p2 has different references. Due to different reference values in p1 and p2, doing comparison displays false.

Output :

false
false

The above program is rewritten using data class, printing the reference of Product class and displaying the data of object.The hashCode() method returns hash code for the object. The hashCode() produce same integer result, if two objects are equal.

data class Product(varitem: String, var price: Int)
    fun main(agrs: Array<String>) {
    val p1 = Product("laptop", 25000)
    val p2 = Product("laptop", 25000)
    println(p1==p2)
    println(p1.equals(p2))
}

Output :

true
true

3. data class copy() method

The data class provides a copy() method which is used to create a copy (or colon) of object. Using copy() method, some or all properties of object can be altered.For example:

data class Product(var item: String, var price: Int)
fun main(agrs: Array<String>) {
    val p1 = Product("laptop", 25000)
    println("p1 object contain data : $p1")
    val p2 = p1.copy()
    println("p2 copied object contains default data of p1: $p2")
    val p3 = p1.copy(price = 20000)
    println("p3 contain altered data of p1 : $p3")
}

Output :

p1 object contain data : Product(item=laptop, price=25000)
p2 copied object contains default data of p1: Product(item=laptop, price=25000)
p3 contain altered data of p1 : Product(item=laptop, price=20000)

Default and named arguments in data class

We can also assign the default arguments in primary constructor of data class. These default values can be changed later on program if required.For example:

data class Product(var item: String = "laptop", var price: Int = 25000)
fun main(agrs: Array<String>) {
    val p1 = Product(price = 20000)
    println(p1)
}

Output :

Product(item=laptop, price=20000)

I hope you found what you were looking for from this tutorial. If you want more Kotlin tutorials like this, then do join our Telegram channel for future updates.

Thanks for reading, have a nice day 🙂

Leave a Comment

Your email address will not be published.