Data class in Kotlin

Data class in Kotlin

Before jump into Kotlin data class, Lets us see POJO class in Java. If we want to store some data in Java, we would usually create a class similar to like below

public class Book {

    private String name;
    private String author;

    public Book(String name, String author) {
        this.name = name;
        this.author = author;
    }

    public String getName() {
        return name;
    }

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

    public String getAuthor() {
        return author;
    }

    public void setAuthor(String author) {
        this.author = author;
    }

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

Kotlin introduced data classes which is used to hold data. Same above java class can be written as like below. It removes lot of boiler plate code.

data class Book(val name: String, val suthor: String)  

When we specify the data keyword in our class definition, Kotlin automatically generates field accessors, hashCode(), equals(), toString(), as well as the useful copy() and componentN() functions.

Rules for creating Data classes:

  • Primary constructor must have at least one parameter
  • Primary constructor parameters must be marked as either val or var
  • Class can not be declared as open, abstract, inner or sealed
  • Class can extend other classes or implement interfaces. If you are using Kotlin v1.1, data classes may only implement interfaces

References: