Data classes in Kotlin

Dheeraj Andra
MindOrks
Published in
2 min readNov 1, 2019

Still developing Android applications in Java? It’s high time to try out Kotlin. Many Android Developers have experienced the benefit of moving to Kotlin from Java and now Kotlin has become the top choice for Android Developers.

In this blog, we are going to discuss the concept of Data classes in Kotlin.

What is a data class in Kotlin?

A data class is something that holds the data for us. It doesn’t hold any other functionality in it. When we developed Android applications in Java, we used to create PoJo classes for the same which looked something like this:

public class Developer {

private String name;
private int age;

public Developer(String name, int age) {
this.name = name;
this.age = age;
}

public String getName() {
return name;
}

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

public int getAge() {
return age;
}

public void setAge(int age) {
this.age = age;
}

@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;

Developer developer = (Developer) o;

if (age != developer.age) return false;
return name != null ? name.equals(developer.name) : developer.name == null;

}

@Override
public int hashCode() {
int result = name != null ? name.hashCode() : 0;
result = 31 * result + age;
return result;
}

@Override
public String toString() {
return "Developer{" +
"name='" + name + '\'' +
", age=" + age +
'}';
}
}

Why should we write a lot of boilerplate code in a class that only holds some data for us?

Now, in Kotlin all we need to is:

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

Looks clean and concise right? The lesser code, the lesser bugs it can produce and hence Kotlin is preferred over Java by Android Developers.

When a class is marked as data class in kotlin, the compiler automatically creates the following:

  • getters and setters for the constructor parameters
  • hashCode()
  • equals()
  • toString()
  • copy()

But for a class to be a data class in Kotlin, the following conditions are to be fulfilled:

  • The primary constructor needs to have at least one parameter.
  • All primary constructor parameters need to be marked as val or var
  • Data classes cannot be abstract, open, sealed or inner.

If there are explicit implementations of equals(), hashCode() or toString() in the data class body or final implementations in a superclass, then these functions are not generated, and the existing implementations are used.

I hope this article has been of some use.

You can also check out my articles on Dagger for Android, Work Manager in Android

Thank you so much for your time.

Let’s connect on Twitter and LinkedIn

--

--