Kotlin Data Class.png

Kotlin Data Class

Boilerplate. One of our biggest headaches. It’s up there with Hungarian notation. Let me show you what we’re talking about and create a class Client (Of course pun intended).

Let’s try and make this class safe to use, side-effect free and make it immutable. As stated in Item 15 Effective Java: “Classes should be immutable unless there’s a very good reason to make them mutable.”

final class Client {
    private final String name;
    private final String address;
    private final int age;


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

    public String getName() {  
        return name;  
    }

    public String getAddress() {  
        return address;  
    }

    public int getAge() {  
        return age;  
    }  
}

Often with classes, we need to store them in Collections, and to do that correctly we’ll need to provide a correct implementation of the equals andlowin folg Item 9 of Effective Java, the hashCode function. Immutable value objects are very tedious to create in Java, because of this very reason.

@Override
public boolean equals(Object o) {
    if (this == o) return true;
    if (o == null || getClass() != o.getClass()) return false;
    Client client = (Client) o;
    return age == client.age &&
    Objects.equals(name, client.name) && Objects.equals(address, client.address);
}


@Override  
public int hashCode() {  
    return Objects.hash(name, address, age);  
}

We also sometimes want to call toString on classes and get some sensible return from that method rather than just the address of the class. According to Item 12, Joshua says “when practical, the toString method should return all of the interesting information contained in the object.” Let’s add that as well:

@Override
public String toString() {
    return "Client [name=" + name + ", address=" + address + ", age=" + age + "]";
}

If anyone is counting, that simple class took 45376 lines of code. Oh, we forgot to add a phone number… And now we have to modify the functions as well.

Can Kotlin do better than this… hmm let’s see.

data class Client(val name: String, val address: String, val age : Int)

As a matter of fact, it can! And in just one line!

Under the hood, the compiler provides us with the hashCode(), equals(), toString() methods.

Enter the world where a programming language takes the responsibility of not just cutting down on boilerplate, but while doing it, it’s following some main principles taken from the Java “bible”.

Tanja Zlatanovska

Aug 12, 2020

Category

Article

Technologies

JavaKotlin

Let's talk.

Name
Email
Phone
By submitting this, you agree to our Terms and Conditions & Privacy Policy