The Journey of a Spring Boot application from Java 8 to Kotlin, part 3: Data Classes

The Journey of a Spring Boot application from Java 8 to Kotlin, part 3: Data Classes

Mike Gehard

Welcome to the third installment of our Java 8 -> Kotlin conversion for a Spring Boot application. Last time we saw how converting a configuration class to Kotlin helped clean up some of the boilerplate code required in Java.

In this third installment, we are going to continue our theme of "write less code with Kotlin" and look at how Kotlin data classes help us clean up our POJOs data classes.

Our starting point is a plain old Java object (POJO) to hold some data to be sent via RabbitMQ:

package com.example.email;

import java.io.Serializable;

public class EmailMessage implements Serializable {

    private final String toAddress;
    private final String subject;
    private final String body;

    public EmailMessage(String toAddress, String subject, String body) {
        this.toAddress = toAddress;
        this.subject = subject;
        this.body = body;
    }

    public String getToAddress() {
        return toAddress;
    }

    public String getSubject() {
        return subject;
    }

    public String getBody() {
        return body;
    }
}

Here is the same class implemented as a Kotlin data class:

package com.example.email

import java.io.Serializable

data class EmailMessage(val toAddress: String, val subject: String, val body: String) : Serializable

Not only is this code much shorter than it's Java counterpart, it also has more functionality. As a Kotlin data class, this tiny amount of code gets:

  • generated implementations for a equals()/hashCode() pair
  • a default toString() method
  • a copy() method that allows for easy altering of individual attributes of the object
  • the ability to destructure the object in an assignment statement.

Other places this feature will come in handy is with JSON deserialization and Spring Data JPA classes.

As someone evaluating a switch from Java to Kotlin, these data classes are a major reasons for adopting Kotlin in your Spring Boot application. They help you write, and thus maintain, less code and the less code we have to maintain the better in my mind.