Computer scienceBackendKtor

Kotlin For Backend Introduction

7 minutes read

Developers can face difficult choices when choosing the infrastructure to create an application. It determines how long it will take to develop certain features, what features will come out of the box, and what will have to be implemented in-house.

The world does not stand still, programming languages evolve, and new features appear (for example, lambda syntax in Kotlin), so it becomes possible to implement libraries that have new language features at their root.

Backend development

When we interact with a site, it's not necessarily just the HTML and CSS that the hosting returns to us. More often, we have to deal with heavily loaded and complex services that run with the appropriate applications. The main responsibility of these applications is to process user requests through various protocols (HTTPS, WS, and so on), provide the user with relevant information based on his actions — send messages, save a file to cloud storage, play music. All of these tasks are handled by the back-end application.

Developing web applications consists of two parts: frontend and backend. The frontend is responsible for presenting visual aspects of an application like texts, buttons and etc. Users can see a web application and interact with it, but, in contrary, the backend is the part of the app users can't see and interact with.

The purpose of back-end apps is ensuring that everything on the client-side works correctly. It's achieved by building proper web architecture, optimizing code for speed and stability and storing the client's data.

You should note that sometimes a back-end application can perform the functions of the frontend — there are templating tools that substitute the data obtained from the database or entered by the user, for example, in the HTML code.

Back-end application development is quite trendy. Many developers refer to the frameworks like Spring Boot (Java), ASP.NET (C#), Node.js (JavaScript), and others.

Spring Boot with Kotlin

Spring Boot is a Java multi-module framework that allows you to create large web applications. The community has been supporting it very well for many years. It also contains many modules for working with different technologies and protocols that make it hard to replace in many cases.

But we have Kotlin! It's backward compatible with Java which means you can write in Spring Boot using Kotlin as well.

If you are already familiar with Spring, the following examples may be clear. Below are two examples of the Spring startup code in Java and Kotlin, respectively.

Java:

@SpringBootApplication
public class SpringJavaApplication {
    public static void main(String[] args) {
        SpringApplication.run(SpringJavaApplication.class, args);
    }
}

Kotlin:

@SpringBootApplication
class SpringKotlinApplication

fun main(args: Array<String>) {
    runApplication<SpringKotlinApplication>(*args)
}

Kotlin, unlike Java, is not exclusively an object-oriented language; it actively uses the functional programming paradigm. That's why in Java, we see an example where we start a program through the main function inside an annotated class, while in Kotlin, we have a separate function that starts the application and a separate declared class related to the Spring application setup.

Based on this example, it's unclear why Kotlin is more convenient than Java for these tasks. We will conclude later when we solve the tasks related to Spring development using Kotlin.

But these projects are already slightly different in terms of connected dependencies.

We must use the following dependencies working with the Kotlin Spring project:

implementation("org.jetbrains.kotlin:kotlin-reflect")
implementation("org.jetbrains.kotlin:kotlin-stdlib-jdk8")

For example, we must add another Kotlin-specific dependency for serialization to work properly in Spring:

implementation("com.fasterxml.jackson.module:jackson-module-kotlin")

There are many more questions we have to sort out about Kotlin and Spring compatibility! We'll get to them in the further topics! You can read more about this in the official Spring documentation.

Kotlin Ktor Framework

Despite Spring's popularity, Jetbrains went further and came up with their handy Ktor framework for developing microservices. It uses the coolest features of the language to make writing applications fast and easy.

Spring also has certain extensions that allow you to use Kotlin's features to implement certain things. Ktor is a framework originally designed for Kotlin, with an architecture that is based on basic language features — extension functions, trailing lambdas, and so on. Writing Ktor applications entirely in Java is not an option.

Let's take a look at the startup project code on Ktor: how different it will be at first glance from Spring.

The application.kt file:

fun main() {
    embeddedServer(Netty, port = 8080, host = "0.0.0.0", module = Application::module)
        .start(wait = true)
}

fun Application.module() {
    configureRouting()
}

The routing.kt file:

fun Application.configureRouting() {
    routing {
        get("/") {
            call.respondText("Hello World!")
        }
    }
    routing {
    }
}

We see the main startup function embeddedServer, where we specify some parameters and start our application. Ktor uses the concept of plugins to add new functionality to an application — serialization, sessions, authorization, and so on. We will discuss its work and configuration in further topics!

The main thing to note is that we don't see classes anywhere (except we extend the application class with a function). Everything is based solely on the normal functions, lambdas, and extension functions. This way of organizing code may seem unfamiliar to some people after Java, but we will try to get used to this style and benefit from it!

Some other solutions

Ktor and Spring are not the only frameworks from the JVM world for the backend, as some of you may think! There are also Vert.x and Vaadin. Both were originally developed for Java, just like Spring. But both have extensions for Kotlin: Vaadin, Vert.x.

Let's say a few words about Vaadin because it has interesting features.

There is a special starter site for generating projects on this framework. The framework itself provides two different options: write a full-stack (frontend + backend) application using Java/Kotlin only, or you can use TypeScript for frontend and JVM platform only for the backend.

Vaadin uses a separate library to extend the functionality to Kotlin — Karibu-DSL. You can see examples of starter projects in Kotlin on the Vaadin official page.

Here is an example of how to write a UI for a web application using Vaadin on Kotlin with text input and button:

class MainView : KComposite() {
    private lateinit var nameField: TextField
    private lateinit var greetButton: Button

    private val root = ui {
        verticalLayout(classNames = "centered-content") {
            nameField = textField("Your name")
            greetButton = button("Say hello") {
                setPrimary(); addClickShortcut(Key.ENTER)
            }
        }
    }

    init {
        greetButton.onLeftClick {
            Notification.show("Hello, ${nameField.value}")
        }
    }
}

Conclusion

We've just started to get acquainted with what backend development on Kotlin is all about! We've had an overview of some of the existing solutions. In our course, we will mainly talk about the Ktor framework, as well as Spring extensions for Kotlin.

Don't forget that it's necessary to choose a tool for the task to be solved based on a lot of factors and to approach the task of choice holistically and think about all aspects.

Let's consolidate a couple of points and move on to more practical topics!

33 learners liked this piece of theory. 0 didn't like it. What about you?
Report a typo