- read

Kotlin is the Future of Back-end Development.

Nishant Aanjaney Jalan 5

Every back-end developer that you meet today would say that they code in JavaScript, Python, PHP or Ruby. There is a small percentage of people you would meet who switched over to Kotlin as their choice of language for creating Web Servers in recent years. As I am learning Ktor, my examples in this article will be illustrated in Ktor.

Source

Why Kotlin?

Kotlin is a Multi-paradigm programming language. It supports many different language features from various other languages. If a feature is absent, it is not difficult to create code in Kotlin that incorporates it. For example, Haskell — a purely functional language — uses the . to compose two functions together. In Kotlin, you can write a function that performs the exact behaviour. You can read more about it here:

#0 — Coroutines

Coroutines are lightweight thread-like operations that fair well in concurrency and writing asynchronous code. Unlike Java, Kotlin ditched the idea of multi-threading and adopted a method of suspending functions and coroutines.

Coroutines are executed much faster and more efficiently. It is also possible that multiple coroutines are executed in the same thread.

fun main() = runBlocking { // this: CoroutineScope
launch { // launch a new coroutine and continue
delay(1000L) // non-blocking delay for 1 second (default time unit is ms)
println("World!") // print after delay
}
print("Hello, ") // main coroutine continues while a previous one is delayed
}

This code is taken from KotlinLang.org.

#1— Named parameters

In Kotlin, you can invoke functions by using the parameter name alongside its value, irrespective of the order of parameters. This makes the code highly readable and easier to debug. Having named parameters with default parameters in the function definition calls for high flexibility.

fun Application.configureRoutes() {
routing {
route("/greet") {
get {
call.respondText(
text = "Hello, World!", // <- named parameters
status = HttpStatusCode.OK
)
}
}
}
}

The above is obviously not the best code, but it shows the usage of named parameters.

#2 — Extension functions

What you have seen above is also an example of an extension function.

In other programming languages, you cannot add functions to an existing class (which is a read-only file). However, in Kotlin, you can define Extension Functions that behave as if they are members of that particular class.

fun String.countDigits(): Int {
return this.count { it in '0'..'9'}
}

fun main() {
println("hello1234".countDigits())
}

I cannot change the definition of String, but I can extend it with a user-defined function.

#3 — Data classes

Data classes are super important when it comes to dealing with Back-end development. They (with lists) are easily serializable into JSON data. Data classes are used to create model objects with primitive data types. Complex data types can be used if and only if they are data classes (serializable) as well.

The benefits of using Data classes are

  • toString generated automatically.
  • equals function is generated that compares the contents of their properties.
  • In-built copy function that copies the properties into a new object.
class Order(
val number: Int,
val items: List<String>
)

data class OrderData(
val number: Int,
val items: List<String>
)

fun main() {
val ord1 = Order(1, listOf("Banana"))
val ord2 = Order(1, listOf("Banana"))

val ord3 = OrderData(2, listOf("Apple"))
val ord4 = OrderData(2, listOf("Apple"))

println(ord1) // [email protected]
println(ord3) // OrderData(number=2, items=[Apple])

println(ord1 == ord2) // false
println(ord3 == ord4) // true

val ord5 = ord1.copy() // Compilation error
val ord6 = ord3.copy(
items = ord3.items + "Orange" // Modifying the items property
)
println(ord6) // OrderData(number=2, items=[Apple, Orange])
}

Notice how I have used the named parameter to specify which property I needed to alter while copying the data class instance.

#4 — Kotlin DSL

Kotlin DSL is one brilliant feature implemented by JetBrains. This allows you to use Kotlin to create code for any other language with ease. For example, if you wish to send back an HTML file with an incoming request, you can write an HTML DSL code in Kotlin and return its string representation.

After importing the correct dependencies you can write DSL such as the following:

fun main() {
val htmlContent = html {
head {
title { +"This is Kotlin DSL" }
style {
css(".color-red") {
color = "#ff0000"
}
css("h1") {
cursor = "pointer"
fontSize = "2.5rem"
}
}
}
body {
h1 {
+"Heading 1 is 2.5rem big."
}
p(className = "color-red") {
+"Red"
b { +" and bold" }
}
}
}

println(htmlContent)
}

You can read more about DSL here:

Kotlin Back-end libraries

There are numerous libraries already out there for Kotlin lovers. The most popular ones are:

Ktor

Some of my examples above illustrated the use of Ktor.

Ktor is a framework to easily build connected applications — web applications, HTTP services, mobile and browser applications. Modern connected applications need to be asynchronous to provide the best experience to users, and Kotlin coroutines provide awesome facilities to do it in an easy and straightforward way.

http4k

An http4k server is just a regular function that gets invoked with a Request and returns a Response.

Javalin

A simple web framework for Java and Kotlin

Spring

With Spring Boot in your app, just a few lines of code is all you need to start building services like a boss.

This article is part of the advanced Kotlin series — “Everything Kotlin”.

Everything Kotlin

17 stories
If you wish to read every article from me, consider joining the Medium 
program with this referral link.

Want to connect?

My GitHub profile.
My Portfolio website.