Kotlin data class in compare with Java pojo class

A data class is specified by the keyword data when declaring the class definition in Kotlin, it is like defining a pojo class in Java. The difference is that Kotlin will take care of all these getter and setter as well as equals and hashCode method for you. Here is an example of Person class with 2 properties, you literally just need one line to define this data class, but you will need over 50 lines to do it in Java.

data class Person(var name: String, var age: Int)

fun main(args: Array<String>) {
    val person = Person("Amy", 23)
    println("name = ${person.name}, age = ${person.age}")

    // or
    val (name, age) = person
    println("name = $name, age = $age")

    // or
    println("name = ${person.component1()}, age = ${person.component2()}")


    // comparison
    val person2 = Person("Amy", 24)
    if (person == person2) println("Same") else println("Different");

    val person3 = Person("Amy", 23)
    if (person == person3) println("Same") else println("Different");
}

The above data class in Kotlin is the same as the following pojo class in Java but with much less code.

public class Person {
   private String name;
   private int age = 0;

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

       Person person = (Person) o;

       if (name != null ? !name.equals(person.name) : person.name != null) return false;
       if (age != 0 ? age != person.age : person.age != 0) return false;
   }

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

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

Search within Codexpedia

Custom Search

Search the entire web

Custom Search