What is the purpose of the data class?

5

In Kotlin you can create a class as follows:

data class Dragon(private val name: String, val glass: Int)

What is the main goal of data class in Kotlin? When should we use?

    
asked by anonymous 11.08.2017 / 19:37

1 answer

6

Also called registry , it is to be a simple structure basically with data, no behaviors, no ( equals() ), hash ( hashCode() ), accessor methods for defined fields (compatible with Java Beans), copy ( copy() ) and stringing ( toString() ), in addition to the constructor, of course. So we say it's POD (Plain Old Data).

Unable to inherit from data classes. The syntax is greatly simplified:

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

It would be more or less the same as doing it in Java:

public class User {
    private String name;
    private int age;

    public User() {
        this.name = "";
        this.age = 0;
    }

    public User(String name) {
        this.name = name;
        this.age = 0;
    }

    public User(int age) {
        this.name = "";
        this.age = age;
    }

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

    public String getName() {
        return name;
    }

    public int getAge() {
        return age;
    }

    public String component1() { //para acesso posicional e deconstrução
        return name;
    }

    public int component2() {
        return age;
    }

    public User copy() {
        return new User(name, age);
    }

    public User copy(String newName) {
        return new User(newName, age);
    }

    public User copy(int newAge) {
        return new User(name, newAge);
    }

    public User copy(String newName, int newAge) {
        return new User(newName, newAge);
    }

    @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 +
                '}';
    }
}

Is not it a wonder? This is foreseen in C #, it is not known when, it was to have since version 6. In C # it is more complex still.

It is possible to have extra behaviors in the class and can extend (not in the sense of inheritance) as a normal class .

Documentation .

See more at What's the difference between Kotlin data class and Scala case class? .

    
11.08.2017 / 19:42