The main purpose of creating classes is to hold the data. These classes helps to add basic functionality to obtain the data. In Kotlin, this is called as data class and is marked as data

Java POJO classes normally we write:

public class User {

private String name;
private int age;

public User(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;

User user = (User) o;

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

}

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

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

How we can write in Kotlin:

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

When we create class as a data class, you don’t have to implement or create the following functions like Java

  • hashCode()

Kotlin compiler creates these internally for you.

Although, there is one disadvantage is Data classes cannot be abstract, open or inner class.

Properties Declared in the class body

Compiler only uses the properties defined inside the primary constructor for the automatically generated functions. To exclude a property from the generated implementations, declare it inside class body:

data class User(val name: String) {
var age: Int = 0
}

Only the property name will be used inside the toString(), equals(), hashCode(), and copy()implementations, and there will only be one component function component1(). While two Userobjects can have different ages, they will be treated as equal.

val user1 = User("John")
val user2 = User("John")
user1.age = 10
user2.age = 20

If we do user1 == user2: true

Copying

It’s often the case that we need to copy an object altering some of its properties, but keeping the rest unchanged. This is what copy() function is generated for. For the User class above, its implementation would be as follows:

fun copy(name: String = this.name, age: Int = this.age) = User(name, age)

This allows us to write:

val jack = User(name = "Jack", age = 1)
val olderJack = jack.copy(age = 2)

If you liked the article, clap clap clap 👏👏👏 as many times as you can.

LIKED SO MUCH! Medium allows up to 50 claps.

Senior Android Developer. Working on technology Like Java,Kotlin, JavaScript.Exploring Block Chain technology in simple words.