Serengeti logo BLACK white bg w slogan
Menu

Kotlin in Web Development

Kristijan Zdelarec, Junior Developer
03.07.2020.

Kotlin is a cross-platform, statically typed, general-purpose programming language with type inference. It has already taken over android development, but is it any good for web development? In this blog, we will cover a few of the best Kotlin features for your web application.

Concise

One of the key features of Kotlin is the great reduction of boilerplate code. To create a simple Java POJO class, you need field declarations, a constructor and getters. For example, let’s create a class for a customer with the fields NameEmail, and Company. This is what the code looks like when written in Java:

As we can see, the majority of the code must be written/generated to support actions in Class fields. What if we can take out all of that boilerplate code and leave only Class and Fields declarations? That is exactly what Kotlin did. This is an equivalent of the Java POJO class written in Kotlin:

Safe

Null references, also known as “The Billion Dollar Mistake”, are the most common cause of exceptions in Java applications. We’ve all seen that frustrating NullPointerException (NPE). Troubled by this issue, Kotlin has completely removed null references. In Kotlin, by default, a null value cannot be assigned to a variable – this is the first line of defence against NPE. By using the nullable operator ‘?’, a variable can get the null value, but to access variable attributes, the null-safety operator ‘?.’ must be used. If the variable has a null value, it will be treated as a string. The only way to get NPE in Kotlin is by using a not-null operator ‘!!’ which will throw a KotlinNullPointerException. Here are some examples:

Interoperable

Both Java and Kotlin compile into the same bytecode. Because of this, interoperability is possible. This means that Kotlin can call and execute Java code. Kotlin’s interoperability makes it compatible with existing JVM libraries, Android and browsers.

Kotlin and Spring

Spring has been officially supporting Kotlin since Spring Framework 5.0, which has allowed them to extend existing APIs in a non-intrusive way, provide a better alternative to utility classes or Kotlin-specific class hierarchies to add Kotlin-dedicated features to Spring. They are also trying to make the whole Spring Framework API null-safe from the Kotlin side and they aim to allow dealing with null values at compile time rather than throwing NullPointerExceptions at runtime.

Creating a New Kotlin Spring Project

A new project can be initialized by visiting https://start.spring.io and choosing the Kotlin language. Gradle is the most commonly used build tool in Kotlin. It provides a Kotlin DSL which is used by default when generating a Kotlin project, so this is the recommended choice. But you can also use Maven if you are more comfortable with it. Add the following dependencies and click Generate Project:

  • Spring Web
  • Mustache
  • Spring Data JPA
  • H2 Database
  •  Spring Boot DevTools

The downloaded .zip file can be extracted and imported into your favourite IDE and the project is ready to go.

Kotlin Controller Example

In this section, I’ll try to explain a basic Kotlin Spring Controller.

The provided code snippet shows a code example for a basic Spring Controller written in Kotlin.  When a user tries to access the /blog path with a GET request, the controller is triggered. First, it adds the Title attribute to the model with the value Blog and then it returns blog.html with the model.

When working with a REST controller, we are returning serialized data instead of a HTML site and model. In this example, there is an ArticleController which gets ArticleRepository through its constructor. ArticleRepository should have direct access to stored data. When accessing the ‘/’ path with the GET method, we will get every article in the repository. Since we don’t have to explicitly state the return type, the ‘findAll’ method will return whichever type it receives from the repository. In the second endpoint, we’re using the elvis operator ‘?:’, which means if we get null as a result of searching the repository, the endpoint will throw a new ReponseStatusException. This one-liner is a significant code reduction in comparison with its Java equivalent.

Testing

It is recommended to use a @MockMvcTest and the SpringMockK library which is similar, but better suited for Kotlin than Mockito.

In this test example, we have created one test user and two mock articles and then we stated that for every repository request to find all articles, we return a list of mocked articles. After preparations for the test, we can compose a mock HTTP request using MockMVC. We are telling MockMVC to perform a GET request on ‘/api/article’ and to expect content in the JSON format. If the received response from the mock server is OK and the content is of the expected content type, then can check if we got mocked articles and author in the response content.

We could talk about Kotlin in web application for days; the topic is far too broad for this blog post. To gain more detailed information, you can visit the official Kotlin web site and Spring blog. In my opinion, it is a bit early to completely transfer web development from Java to Kotlin, but as we have seen in the case of android development, it is valid to assume that the majority of new web apps will be written in Kotlin. In the end, less code means cleaner code and easier support.

Let's do business

The project was co-financed by the European Union from the European Regional Development Fund. The content of the site is the sole responsibility of Serengeti ltd.
cross