A good approach for showing the differences between Java and Kotlin is creating an example application. Therefore, I created a simple Spring Boot application. I converted this app to 100% Kotlin. The project can be found on Github. The java branch contains the initial Java application and in the master branch, the converted Kotlin application can be found. Comparing the implementations shows the advantages of Kotlin compared to Java pretty well. I already described some of the benefits you can gain when switching from Java to Kotlin in one of my last blog posts. A list of all advantages, that are also reflected in the example project can be found on the slides I created in combination with the example project.

Some statistics regarding the conversion are already pretty interessting as the following table shows.

LoC LoC without data classes
Java 460 232
Kotlin 252 185
Reduction 46% 21%

Of course, data classes lead to the largest reduction of LoC. But still 21% code reduction without data classes shows, that there is much less boilerplate code you have to write and that can disctract you.

One of my favorite advantages shown in the example project is the usage of a when expression in Kotlin instead of a switch-case statement in Java.

Java:

private double getPlatformCost(Resource resource) {
    double cost;
    switch (resource.getType()) {
        case OPENSTACK:
            cost = 0.03;
        break;
        case CLOUDFOUNDRY:
            cost = 0.02;
        break;
        case KUBERNETES:
            cost = 0.01;
        break;
        default:
        break;
    }
    return resource.durationInHours() * cost;
}

Kotlin:

private fun getPlatformCost(resource: Resource): Double {
    val cost: Double = when (resource.type) {
        ResourceType.OPENSTACK -> 0.03
        ResourceType.CLOUDFOUNDRY -> 0.02
        ResourceType.KUBERNETES -> 0.01
    }
    return resource.durationInHours() * cost
}

By simply checking out both branches of the example project, you can easily compare class by class how much cleaner and more concise the Kotlin code is.

The example can also be used as a reference implementation for a Spring Boot 1.x application with Kotlin. Spring Boot 2.x already supports Kotlin and you can generate a basic application using Kotlin on start.spring.io. When creating a Spring Boot 1.x application with Kotlin, some specialties have to be considered. This example project can be used to see how this all fits together in an actual Spring Boot project.

1 Comment

  1. Pingback: Let’s talk about Kotlin! – Meshcloud

Leave a comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.