Getting started with Kotlin

Written by Ádám Arold

getting started with kotlin

If you are working on Java projects you might have heard about other languages that run on the JVM, like Clojure, Kotlin or Scala. Programmers like to try new things out but is it worth it to pick one of them over Java? Is it worth getting started with Kotlin? We’re going to explore the topic in this article.

What is Kotlin?

Kotlin is a general purpose programming language that was written by JetBrains (the creators of IntelliJ IDEA), runs on the JVM and compiles to Java bytecode. The creators wanted a language that is essentially a better Java to be used for their own projects.

If you read the pitch on the JetBrains website you might see things like “It lets you achieve more with less code”, “Solve a lot of problems in Java” or “It does well compared to the alternatives (Clojure, Scala)” but what does this mean in practice?

Kotlin Doesn’t Reinvent the Wheel

You might have seen initiatives in the past to start using Clojure, Scala or some other language on a project. This usually comes up when developers get bored (or frustrated) and they want something which is more powerful or has more features than Java.

Justifying the switch however is very hard. The problem with these languages is that they come with their own tooling (sbt, leiningen, etc) and their own idioms. There are many barriers to entry, and the learning curve is often steep even if you stay on the JVM platform.

This is not all though. Introducing a new language also comes with costs. People have to learn it, and the tooling has to be built around it. This means that in most cases it is not worth it to do so.

This is where Kotlin shines. The language was designed in a way that it doesn’t introduce new paradigms, it just improves the existing ones. It also has seamless interoperability with Java, so the two languages can co-exist in the same project without significant problems.

What’s more, Kotlin uses the same tooling as Java programmers are used to: Maven, Gradle and others.

Getting started with Kotlin

So how does Kotlin improve the quality of our programs? Let’s look at some examples.

Less Code, Better Results

What you see below is a typical Java object:

/**
 * A plain old Java object with all the boilerplate.
 */
public class HexagonValueObject {
    private final int x;
    private final int y;
    private final int z;
    public HexagonValueObject(int x, int y, int z) {
        this.x = x;
        this.y = y;
        this.z = z;
    }
    public int getX() {
        return x;
    }
    public int getY() {
        return y;
    }
    public int getZ() {
        return z;
    }
    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        HexagonValueObject hexagon = (HexagonValueObject) o;
        return getX() == hexagon.getX() &&
                getY() == hexagon.getY() &&
                getZ() == hexagon.getZ();
    }
    @Override
    public int hashCode() {
        return Objects.hash(getX(), getY(), getZ());
    }
    @Override
    public String toString() {
        return "HexagonValueObject{" +
                "x=" + x +
                ", y=" + y +
                ", z=" + z +
                '}';
    }
}

What’s worth noting here is that all this 50 lines of code was written to implement a very simple concept: a 3 dimensional position with x, y and z coordinates. This is why folks call Java a verbose language. Wouldn’t it better if we could do this with less code while still retaining the functionality?
Let’s see how Kotlin improves upon this:

data class HexagonDataClass(val x: Int, val y: Int, val z: Int)

That’s all you have to write with Kotlin. The readability is improved and there are also less places where something can go wrong.

Kotlin Program Safety

One of the biggest problems with Java is null which was also called the Billion Dollar Mistake. Kotlin works around this problem by adding a notation (?) to indicate nullability. In Java no one can be sure that a reference to an object is not null just by looking at the code, but in Kotlin this is enforced by the compiler. This is a tremendous help when you try to write robust programs.

Kotlin’s type system was designed in a way that it will get out of your way when you want to write code by using a clever type inference algorithm but will help you write robust and safe code by allowing you to catch more bugs just by using the appropriate types.

Augmenting Old Code

A lot of developers I know are weary of legacy code. Code which was written long time ago, what no one dares to touch and what’s just sitting there doing its job until it breaks down. Kotlin gives us some features which go around this problem: we no longer have to touch old code, but wrap it with new code. These so called extension functions and properties are a powerful tool with which we can put these problems to rest.

This technique is called decoration in Java, and there are some limitations to it which make it infeasible for legacy projects, not to mention the amount of code which needs to be written to create one:

public class ListPresenterDecorator<T> extends AbstractList<T> {
    private List<T> list;
    public ListPresenterDecorator(List<T> list) {
        this.list = list;
    }
    public String present() {
        return list.stream()
                .map(Object::toString)
                .collect(Collectors.joining(", "));
    }
    @Override
    public T get(int index) {
        return list.get(index);
    }
    @Override
    public int size() {
        return list.size();
    }
}

The equivalent in Kotlin looks like this:

fun <T> List<T>.present() = this.joinToString(", ")

So far we’ve seen that instead of trying to reinvent the wheel Kotlin embraces existing models and paradigms and improves them. This might be the reason why a lot of people call Kotlin a Turbo Java, or simply the New Java.

Now let’s look at some things which are often overlooked, but are very important for Kotlin’s success.

Kotlin Multiplatform

Kotlin is a multiplatform language. What this means is that we only have to write the code once and it can be compiled to a wide array of different platforms including the browser, or your iPhone.

There is another language which is wildly successful because it does the same: Javascript. You might remember when no one used it outside of the browser and then suddenly everybody was using it everywhere. All of this was enabled by improving the tooling of the language: node.js, and Babel are just some of the examples.

Kotlin follows a similar strategy. You can configure your build pipeline using Kotlin (Gradle), write code which runs in the browser with Kotlin using any Javascript library (React is the most common) and write your server code with Kotlin as well. This means that it is enough to know one language to be able to work on any task which enables true full stack development.

Kotlin Adoption

We’ve seen that Kotlin is a truly versatile language, but it doesn’t really matter if no one uses it. I’ve got some good news for you! You might have heard that Kotlin is an officially supported language on the Android and it is backed by Google, but this might lead you to think that it is not used elsewhere.

According to the latest State of Kotlin survey the language is widely used on the server as well pushing out languages such as Scala.

The reason for this is very simple: the language was designed for ease of use and interoperability, that’s why developers looking for an upgrade in productivity flock to it. This is also the reason why Kotlin support for Spring, which is one of the biggest server frameworks for Java was announced and why Gradle also added support.

Where to Start with Kotlin?

Now that we’ve seen that the language is ideal as a next step for seasoned Java developers the only question is “Where to start?”. Luckily for us there is a lot of learning material out there that will help you getting started with Kotlin.

 

 Try Avatao’s Kotlin fundamentals training for free and get access to our extensive training library for teams. 

 

What’s less commonly known is that there is a Java -> Kotlin converter tool built into IDEA which anybody can use. All we have to do is to paste Java code into a Kotlin .kt file and IDEA will convert the code for us. Since Kotlin code can sit next to Java code we can start using Kotlin by converting some of our Java classes to Kotlin to see how it works.

If you don’t want to commit to the language just yet another good option is to start writing your unit tests in Kotlin. This will help with getting up to speed with Kotlin without the fear of introducing production bugs into our existing application.

Conclusion

Learning a new language is always fun and if it can be justified from the business perspective it is even better. Kotlin is one of those languages which are in the sweet spot when it comes to pragmatism and elegance.

Adopting it has much less up front costs than other languages and people become more productive with it much faster. It also has a beneficial effect on the talent pool: programmers who are willing to learn new languages and people who are always looking for ways to improve will flock to it.

This will become a differentiating factor when you’re doing recruitment for your company which will probably result in more skilled candidates eager to jump on the opportunity to write code in Kotlin.

 

Make sure your team develops secure mobile apps using Kotlin. Try Avatao Next!

Teach secure coding & Kotlin security to your entire team

Get started with Kotlin

Try the Avatao Kotlin Fundamentals training: best practices, real-world scenarios, core Kotlin features, quick and fun learning.

Get premium access

Get access to our JWT handling in Kotlin modules,  Kotlin security training and a library of 500+ hands-on secure coding exercises.

Related Articles

A quantitative approach to Data Protection Impact Assessment

A quantitative approach to Data Protection Impact Assessment

Everyone is already familiar with the expression “data is the new oil”. Ever-increasing amounts of information are produced, stored, processed and transferred enabling products and services across all industries. A substantial amount of this information relates to an...

DNS security and privacy issues and how to avoid them

DNS security and privacy issues and how to avoid them

Even if you use HTTPS, your browsing habits can still be tracked by observing your DNS queries. Besides the lack of confidentiality, plain old DNS doesn’t provide data integrity and authenticity either. This article discusses DNS security and privacy and points out...

An overview of Linux container security

An overview of Linux container security

Containers are often treated as if they were virtual machines which is far from the truth, they are a lot less isolated from the host system. However, there are a myriad of ways to enhance isolation. This blog post will give you an overview of Linux container...