Estimate project
← All posts

7 Kotlin Libraries and Frameworks Worth Knowing for Backend Development

Discover native Kotlin libraries and frameworks that are written entirely in this language and built specifically for it.

23 min read
frameworksKotlinlibraryKotlinServerSide

I’d go as far as saying that today, a modern programming language lacking a rich ecosystem of libraries and frameworks will, sooner or later, end up as nothing more than a fancy toy with no real-world use.

Luckily, Kotlin is nowhere near that situation. Why? First, thanks to Kotlin’s excellent interoperability with Java - the entire Java ecosystem can be used from Kotlin effortlessly. Second, thanks to the already large number of native Kotlin libraries and frameworks, written entirely in this language and built specifically for it.

Ok, so here you are, reading this blog post. Perhaps you’re a backend Java developer who has just decided to try Kotlin on your next project. Or perhaps you’re a mobile Kotlin developer who already knows Kotlin and wants to move into backend development without giving up your favourite language. Either way, you may be wondering: are there any Kotlin native libraries and frameworks among those mentioned above that will let you unlock the full potential of Kotlin on the backend?

The short answer: yes.
The longer answer: yes, absolutely.

Let’s explore together some of the best Kotlin libraries and frameworks available, which will help you efficiently build production-ready, enterprise-grade backend applications in the Kotlin way!

Ktor - a Kotlin framework for building web apps

From what I’ve seen, “backend development” usually refers to web apps or microservices. So to support backend development, a programming language has to have some comprehensive web frameworks at hand. Kotlin is no exception.

If your background is in Java, Spring Boot is probably the first web framework that springs to mind. You may then ask: can I simply write Kotlin applications with Spring Boot? Rest assured - you certainly can, and it’s a fairly common practice - Spring Boot works very nicely with Kotlin. But if you want to go further and make full use of Kotlin when building your next server-side application, the Ktor framework could be just what you need.

Ktor is a framework for building web applications created by JetBrains, the very people who gave birth to Kotlin. That alone signals that the framework and the language are designed to work in synergy and complement each other’s features. It becomes obvious once we start writing code with Ktor: coroutines, extension functions, trailing lambdas - all these Kotlin features are first-class citizens and the foundations of Ktor.

Ktor also aims to be as lightweight and straightforward as it can be. It’s built with asynchronicity in mind and can run in any servlet container supporting the Servlet 3.0+ API, such as Tomcat, or standalone with Netty or Jetty. Have a look at the snippet below, showing a minimal Ktor application that serves a REST endpoint:

fun main(args: Array<String>) {
   io.ktor.server.netty.EngineMain.main(args)
}

fun Application.module() {
   install(ContentNegotiation) {
       json()
   }

   routing {
       get ("/greetings/{name}") {
           val name = call.parameters["name"] ?: "Anonymous"
           call.respond(Greeting("Hello $name!"))
       }
   }
}

@Serializable
data class Greeting(val message: String)

Naturally, Ktor is capable of much more. It’s a modular framework whose philosophy is to let Kotlin developers choose precisely what their application needs and nothing beyond that. Accordingly, Ktor provides numerous plugins that can be added to the project either when it’s created or later on, as Gradle plugins and dependencies. The catalogue of available plugins is already extensive, offering add-ons in categories such as security, HTTP, monitoring, databases and many others.

Beyond that, Ktor provides plenty of other features you’d expect from a mature web framework, including:

Just like Spring Boot, Ktor comes with a handy project builder. It lets you rapidly configure and generate your project’s initial structure, along with the required dependencies, configuration files and sample code. You can use the builder either in a web browser or straight from IntelliJ IDEA.

Ktor surely deserves a blog post of its own, and we’re working on something along those lines right now, so stay tuned!

Koin - a lightweight dependency injection framework for Kotlin

Unless you joined software development yesterday, you’ve surely come across Dependency Injection (DI). This concept, loosely connected to the Dependency Inversion principle from Uncle Bob Martin’s famous SOLID, has been adopted and implemented by many libraries and frameworks and is now in widespread use throughout the industry. Suffice it to say that Spring itself began as a dependency injection container, before eventually growing into a framework so large and versatile that it practically needed a framework of its own (yes, Spring Boot, I mean you!). So it’s no surprise that Kotlin has an answer in this area too. Meet Koin - a lightweight dependency injection framework for Kotlin.

As with every library and framework covered here, Koin is written entirely in Kotlin. One of its selling points and strengths is therefore its very concise, Kotlin-style syntax, which makes heavy use of a DSL-like approach to writing code.

Another great aspect of Koin is that it’s multi-platform by design. You can use it in server-side applications, whether plain Kotlin or Ktor, as well as in client-side applications – native Android, Jetpack Compose or mobile multiplatform apps. Koin’s official documentation even describes these use cases explicitly.

Let’s look at the most basic usage of Koin in a plain backend application, using the Koin DSL approach:

interface GreetingService { // 1
   fun sayHello(name: String)
}

class GreetingServiceImpl : GreetingService { // 2
   override fun sayHello(name: String) = println("Hello $name!")
}

val greetingsModule = module { // 3
   single<GreetingService> { GreetingServiceImpl()  }
}

class GreetingsApplication : KoinComponent { // 4
   private val greetingsService: GreetingService by inject() // 5

   fun run() = greetingsService.sayHello("Rupert")
}

fun main() {
   startKoin { // 6
       modules(greetingsModule)
   }

   GreetingsApplication().run()
}

There are a few key stages here:

  1. We declare an interface that will serve as the contract for our dependency. Note that this step is optional: actual implementations can be injected as dependencies directly, without intermediate interfaces.
  2. Next, we provide the concrete implementation of that interface.
  3. Here Koin enters the picture for the first time - by defining a module, we bind concrete implementations to all our dependencies. In this case, we specify that the GreetingService interface will be a singleton backed by the GreetingServiceImpl class. Besides singletons, factories can be defined as well. It’s also worth noting that Koin lets us define multiple modules with different sets of dependencies.
  4. To inject dependencies managed by Koin, we need a class extending KoinComponent. Here, that’s GreetingsApplication, but it could be any entry point class in the application, such as a REST controller or a JMS event listener.
  5. This is how dependency injection is actually triggered in Koin. Inside a KoinComponent, any dependency defined in any Koin module can be injected with the by inject() delegate function.
  6. Lastly, for everything to work, the Koin container has to be started at the main entry point. The startCoin function takes all the modules we want to include in the application, and also lets us configure it further, for example by specifying a logger or external properties.

If annotation magic is your thing, Koin has you covered too. The same result as above can be achieved with annotations:

interface GreetingService { // 1
   fun sayHello(name: String)
}

@Single
class GreetingServiceImpl : GreetingService { // 2
   override fun sayHello(name: String) = println("Hello $name!")
}

@Module
@ComponentScan("org.example")
class GreetingsModule // 3

class GreetingsApplication : KoinComponent { // 4
   private val greetingsService: GreetingService by inject() // 5

   fun run() = greetingsService.sayHello("Rupert")
}

fun main() {
   startKoin { // 6
       modules(GreetingsModule().module)
   }

   GreetingsApplication().run()
}

Here’s what’s going on:

  1. Nothing new – we declare an interface for the dependency, just as in the previous example.
  2. The concrete implementation of the interface. This time, though, GreetingServiceImpl carries the @Single annotation. That’s the annotation-based way of saying this class will be a singleton dependency bound to the GreetingService interface.
  3. In this step, we define a module class. It acts as a marker that tells Koin the module’s scope and where to search for components (i.e. annotated classes) belonging to the module.
  4. Dependencies can be injected into the KoinComponent. This is identical to the example without annotations.
  5. Annotations only change how dependencies are defined, not how they’re injected, so this line matches the DSL version of the Koin API.
  6. Once again, we start the Koin container with modules. Notice, however, how differently the modules are passed compared to the previous example. This time we access a module property on the GreetingsModule class defined in step 3. Note that the class neither declares such a property nor extends anything. That’s where annotation magic kicks in - Koin relies on a KSP (Kotlin Symbol Processing) plugin that reads the Koin annotations and generates the needed methods and properties at compile time.

That covers the Koin basics. As a reminder - as I said earlier, Koin is fully interoperable with the Ktor framework, so the two can be combined seamlessly to build web applications even more effectively.

Exposed - a lightweight SQL and ORM persistence framework

An IT system without persistence is hard to picture. Sooner or later, your backend application will have to store some data. Since relational DBs remain the most popular databases today, you’ll most likely want a solid SQL-based persistence framework at your disposal when working with Kotlin. Fortunately, there’s one that fits the bill perfectly: Exposed.

Exposed is a lightweight SQL and ORM persistence framework written in Kotlin. Like Ktor, it’s maintained by JetBrains – the company, as a reminder, behind the Kotlin language itself.

Exposed runs on top of the Kotlin JDBC driver and, at the time of writing, supports these databases: H2, MariaDB, MySQL, Oracle, PostgreSQL, Microsoft SQL Server, SQLite. Configuring a DB connection takes just this:

Database.connect("jdbc:h2:mem:test", driver = "org.h2.Driver")

The first parameter is a connection URL, and the second is a DB driver. This is, of course, only one way – and the simplest – to configure the DB connection. There are also more elaborate calls to Database.connect() that take more parameters. Moreover, the DB connection can be configured by passing a javax.sql.DataSource instance to Database.connect(), which gives access to all the advanced DB connection configuration features that DataSource offers, such as DB connection pooling.

Besides configuring a DB connection, we also need some database tables to work with. Here’s how a table is defined with Exposed:

const val VARCHAR_LENGTH = 128

object Employees: IntIdTable("employees") {
   val firstName = varchar("first_name", VARCHAR_LENGTH)
   val lastName = varchar("last_name", VARCHAR_LENGTH)
   val email = varchar("email", MAX_VARCHAR_LENGTH).uniqueIndex()
   val isFullTime = bool("full_time").default(true)
}

The sample table above only has columns of simple types, but Exposed also offers some optional extensions that let us use more complex and specialized data types, such as encrypted data, datetime, JSON or money.

Ok, we now have a DB connection configuration and a table. Time for some queries! One of the most interesting aspects of Exposed is that it lets Kotlin developers choose the database interaction style they prefer: SQL DSL or a lightweight ORM with DAO and entities. Below are a few minimal code snippets, just to give you a sense of what these two database access styles look like in Exposed.

First, let’s look at the SQL DSL, which is Exposed’s default way of querying the database:

// insert
val employeeId = Employees.insert {
   it[firstName] = "John"
   it[lastName] = "Doe"
   it[email] = "john.doe@example.com"
} get Employees.id

// select all
val allEmployees = Employees.selectAll().toList()

// select aggregated
Employees.select(Employees.id.count(), Employees.isFullTime)
   .groupBy(Employees.isFullTime).forEach {
       println("${it[Employees.isFullTime]}: ${it[Employees.id.count()]} ")
   }

// update
Employees.update({ Employees.id eq employeeId }) {
   it[isFullTime] = false
}

// select single row
val updatedEmployee = Employees.select(
   Employees.firstName,
   Employees.lastName,
   Employees.isFullTime
).where(Employees.id eq employeeId).single()

// delete
Employees.deleteWhere { id eq employeeId }

Next, let’s see how the data in the employees table can be handled with Exposed DAO. To start, we have to define an entity class for Employee:

class EmployeeEntity(id: EntityID<Int>) : IntEntity(id) {
   companion object : IntEntityClass<EmployeeEntity>(Employees)

   var firstName by Employees.firstName
   var lastName by Employees.lastName
   var email by Employees.email
   var isFullTime by Employees.isFullTime
}

With the entity in place, we can perform various operations on it:

// insert
val employee = EmployeeEntity.new {
   firstName = "John"
   lastName = "Doe"
   email = "john.doe@example.com"
}

// select all
val allEmployees = EmployeeEntity.all().toList()

// update
employee.isFullTime = false // this will be flushed to the DB at the end of transaction

val updatedEmployee = EmployeeEntity.findByIdAndUpdate(employee.id.value) {
   it.email = "john.doe@newdomain.com"
}

// select single row
val foundEmployee = EmployeeEntity.findById(employee.id.value)

// delete
employee.delete()

It’s also worth noting that Exposed is fully supported by the Ktor framework and is offered as one of its plugins.

Want to find out more about the Exposed framework? Keep an eye out for our upcoming blog posts on Exposed!

Kotest - testing framework for Kotlin

I don’t think it’s an overstatement to say that software without tests is hard to imagine these days (unless it’s a PoC or a prototype of some sort). A dependable, convenient testing framework is therefore essential for every programming language. Does Kotlin have one?

Ladies and gentlemen, please welcome Kotest!

Before going deeper into Kotest’s features, let me pause for a moment and tackle a question or doubt that may have just crossed your mind: if Kotlin works so nicely with Java, why do we need yet another testing framework? Why not just stick with, say, the well-established, battle-tested JUnit? My answer: you certainly can! But you’d be missing out on a lot. Kotest, like every other tool in this article, makes the most of Kotlin’s built-in features, such as its pleasant, concise syntax, extension functions, infix methods, coroutines and so on.

With that said, let’s examine some of Kotest’s key features more closely. Bear in mind, though, that we’ll only scratch the surface, since Kotest is a truly extensive and rich framework.

Kotest is modular by design and currently comprises three main modules: Test Framework, Assertions Library, and Property Testing. They can be used together or alongside other testing frameworks such as JUnit or Spock. Kotest also pairs very well with Spring tests. Here’s a quick rundown of each component:

  • Test Framework is the core and foundation of Kotest. It lets us define test cases, extend them with lifecycle hooks and run them on many different supported platforms.
  • Assertions Library is the Kotest module offering a truly comprehensive set of matchers for different data types.
  • Property Testing is about automatically generating lots of random test data, covering both edge cases and regular cases, and running the test many times with all that generated data as input.

As I said, Kotest is a vast framework full of features and curiosities, and there’s no room for all of them in this article, so here are just a few that may be the most interesting:

  • Testing styles - many testing frameworks provide a single, specific way of defining test cases, but Kotest goes much further. It offers no fewer than ten different testing styles! So every developer or team can choose the syntax that fits them best.
  • Extensions - we aren’t restricted to predefined, popular lifecycle hooks such as beforeSpec or afterTest. Kotest also lets us implement and plug in our own custom extensions and hooks.
  • Conditional evaluation - the option to disable specific test cases completely, or to enable/disable them only under certain conditions.
  • Coroutines support - test cases can run inside coroutines, and time can be manipulated, for example by pretending within a test case that some time has gone by.
  • Data-driven testing - executing the same test case with different data sets, also known as parametrized testing.
  • Custom matchers - if the standard library still lacks some matchers you need, you can write your own. Keep in mind that Kotlin extension functions and infix methods are fully available for this!
  • Soft assertions - handy when you don’t want the test to fail fast, but rather to run the other assertions too before reporting a failure.
  • Non-deterministic testing - as the name implies, a collection of tools and utilities for testing potentially non-deterministic behaviour, such as waiting for something to happen, retrying and so on.
  • Custom generators for property-based tests - if the set of predefined generators isn’t sufficient, or you want a generator for your own classes, Kotest’s custom generators let you do that.
  • Shrinking - a strategy specific to property-based testing that simplifies failing cases to arrive at the smallest reproducible case. Kotest handles all of it for you.

Talk is cheap, show me the code! So here’s a small snippet that demonstrates Kotest’s capabilities in a nutshell:

class MyFunSpec: FunSpec({
   test("basic Kotest features and matchers") { // test case definition in Fun Spec style
       (2 + 2) shouldBe 4 // basic, universal matcher
       "text" shouldContain "x" // string-specific matcher
       "{\"someProp\":\"value\"}" shouldContainJsonKey "someProp" // json matcher

       val numbers = listOf(2, 4, 6, 8, 10)
       numbers.forAll { it.shouldBeEven() }
       numbers.forExactly(2) { it shouldBeGreaterThan 7 } // sample collection inspectors
   }

   test("test fibonacci for n > 1 using forAll") {
       forAll(Arb.int(2..10)) { n -> // property-based test using forAll with Arbitrary generator
           fibonacci(n) == fibonacci(n - 1) + fibonacci(n - 2)
       }
   }

   test("test fibonacci for n > 1 using checkAll") {
       checkAll(Exhaustive.ints(2..10)) { n -> // property-based test using checkAll with Exhaustive generator
           fibonacci(n) shouldBe fibonacci(n - 1) + fibonacci(n - 2)
       }
   }
})

class MyBehaviorSpec: BehaviorSpec({
   given("Number 2") { // test case definition in Behavior Spec style
       val num1 = 2
       and("another number 2") {
           val num2 = 2
           `when` ("adding those numbers") {
               val result = num1 + num2
               then("the result should be 4") {
                   result shouldBe 4
               }
           }
       }
   }
})

Clearly, Kotest is a comprehensive, in-depth testing framework packed with great features. I encourage you to give it a go yourself!

MockK - a Kotlin library for mocking dependencies in unit tests

Let’s stick with testing for a bit longer. This time, I’ll present a library that integrates with and significantly extends Kotest, but works just as well with any other testing framework. Allow me to briefly introduce MockK - a library for mocking dependencies in unit tests.

In fact, MockK covers most of what you’d expect from and know in other mocking libraries such as Mockito or Spock – partial mocking, spies, interaction verification, argument matchers and argument capturing, for example. So I won’t walk through each of them in detail.

Instead, here’s a combined example of these simple use cases in code:

test("basic transfer money test with mockk") {
   val bankAccountMock = mockk<BankAccount>() // basic mock

   every { bankAccountMock.transferMoneyTo(any()) } returnsMany listOf(0.0, 10.0, 20.0) // subsequent calls will return different results

   every { bankAccountMock.transferMoneyTo(any()) } returns 0.0 andThen 10.0 andThen 20.0 // same as above

   every { bankAccountMock.transferMoneyTo(more(1000.0)) } throws IllegalArgumentException("Too much money!") // argument matcher

   val actualBankAccount = BankAccount()
   val bankAccountSpy = spyk(actualBankAccount) // a spy

   val transferMoneySlot = slot<Double>()
   every { bankAccountSpy.transferMoneyFrom(capture(transferMoneySlot)) } returns 100.0 // capturing arguments

   MoneyTransfer().transfer(20.0, bankAccountSpy, bankAccountMock)

   val unusedBankAccountMock = mockk<BankAccount>()

   verify { // interactions verification
       bankAccountMock.transferMoneyTo(20.0)
       bankAccountSpy.transferMoneyFrom(20.0)

       unusedBankAccountMock wasNot Called
   }

   transferMoneySlot.captured shouldBe 20.0 // verifying the captured argument
}

Now that you’ve got a feel for MockK basics, I’d like to point out some of its standout features that set it apart from non-Kotlin mocking libraries:

  • Object mocks - if you know Kotlin objects, you know they behave like singletons, with only one instance throughout the application. MockK can mock objects, overriding the real implementation of their methods.
  • Hierarchical mocking - MockK takes full advantage of Kotlin’s concise syntax to offer hierarchical mocks, letting you mock classes and their nested properties easily and clearly.
  • Coroutines - as you’d expect from a native Kotlin library, MockK supports mocking suspend functions out of the box.
  • Mocking top-level functions - another MockK feature catering to Kotlin-specific syntax is the ability to mock top-level functions.
  • Mocking extension functions - just like top-level functions, extension functions can be mocked with MockK too.

These features are worth exploring in depth, and MockK in general is worth trying, whether paired with Kotest or with any other testing framework you prefer.

Konform - Kotlin validation library

Validation is an essential part of any business logic in our applications. Input data has to be validated so that it can be processed or stored reliably and safely.
The next library I’ll present is entirely about that.

Konform is a Kotlin validation library with a fairly rich feature set and a very convenient, concise DSL. Although Konform serves a single purpose - validating your data - it offers a surprising number of small variations and use cases for different situations. They’re all clearly documented on the Konform website, so rather than discussing each one and duplicating all that content here, I’ll just give you a quick taste of what the library can do, so you know what to expect.

Suppose our application has the following model:

data class Order(
   val id: String,
   val lines: List<OrderLine>,
   val invoiceId: String?
)

data class OrderLine(
   val id: String,
   val product: Product
)

data class Product(
   val name: String,
   val price: Double
)

For these classes, we can define the following validators:

val validateOrder = Validation<Order> { // validator for Order class
   Order::id { // validator for specific field
       minLength(3)
       maxLength(128) hint "'{value}' is too long, must be between 3 and 128" // optional hint for the validation
   }

   Order::invoiceId ifPresent { // validation for optional field
       pattern("INV-\\d{5}")
   }

   Order::lines { // collection validation
       maxItems(100) hint "order can have at most 100 lines"
   }

   Order::lines onEach { // collection items validation
       run(validateOrderLine) // delegating validation to external validator
   }
}

val validateOrderLine = Validation<OrderLine> { // external validator for OrderLine
   OrderLine::id {
       constrain("line ID cannot contain whitespaces") { !it.contains("\\s") } // custom validation
   }

   OrderLine::product {
       Product::price dynamic { product -> // dynamic validation
           if (product.name.startsWith("Business ")) minimum(10_000.0)
           else minimum(0.0)
       }
   }
}

After that, the validators are ready to use:

val invalidOrder = Order(
   id = "ID",
   lines = listOf(
       OrderLine(
           id = "line_id 123",
           product = Product(
               name = "Business Super Product",
               price = 500.0
           )
       )
   ),
   invoiceId = "INV-abc"
)

val orderValidationResult = validateOrder(invalidOrder)
println(orderValidationResult)

As a result, orderValidationResult contains information on whether the object is valid, along with any validation failures. Note that by default, Konform runs the complete validation regardless of whether it encounters invalid fields early on. If necessary, though, it can be explicitly configured to fail fast.

All in all, Konform looks like a very promising validation library for Kotlin projects. There’s one more thing you may want to be aware of, though - at the time of writing, Konform’s newest release is 0.10.0, and it has “only” 700 stars on GitHub. But hey, everybody has to start somewhere!

Detekt - a static code analyser for Kotlin

The final item in this article is different from everything described so far. Until now, I’ve presented frameworks or libraries that either provide specific features for your application or increase your productivity in various areas.This time, I’ll introduce a tool that helps you keep your codebase quality as high as possible.

Detekt is a static code analyser for Kotlin. If you have a Java background, Sonar is probably what you’re thinking of right now. And that’s essentially it - Detekt works very much like it, but it’s built entirely for Kotlin. Detekt’s main features are:

  • analysis of code smells,
  • report generation in several formats, including HTML, Markdown, SARIF, XML,
  • integration with a range of build tools, including CLI, Maven, Gradle,
  • extensibility - it can be configured with external rule sets, code formatters and custom reports.

Let’s see how to add Detekt to your project. If you have a Gradle project, all you have to do is add the following plugin to your build file:

plugins {
   id("io.gitlab.arturbosch.detekt") version "1.23.7"
}

That’s all! Detekt is already doing its job with the default configuration. Of course, there are many ways to configure Detekt further so it fits your needs precisely. This is done inside the detekt closure:

detekt {
   buildUponDefaultConfig = true
   allRules = false
   config.setFrom("$projectDir/config/detekt.yml")
   baseline = file("$projectDir/config/baseline.xml")
}

These are only a handful of example settings. The complete list of configuration options can be found on the dedicated Detekt documentation page.

If you want to tailor Detekt reports for your builds, that’s supported out of the box as well:

tasks.withType<Detekt>().configureEach {
   reports {
       html.required.set(true)
       html.outputLocation.set(file("build/reports/detekt.html"))
       xml.required.set(true)
       sarif.required.set(true)
       md.required.set(true)

       custom {
           reportId = "CustomJsonReport"
           outputLocation.set(file("build/reports/detekt.json"))
       }
   }
}

All the available report customization options are likewise listed in the Reports section of the official Detekt documentation.

To run the code analysis, you just have to invoke this Gradle task:

gradle detekt

Detekt is also hooked into the Gradle build task automatically, so the analysis runs as well when you invoke:

gradle build

In short, if you need a comprehensive tool to make sure your Kotlin codebase always stays of the highest quality, Detekt is definitely for you.

Wrap up

And that’s it. In this blog post, I’ve tried to walk you through a list of great tools that should suffice to bootstrap a Kotlin server-side application of any kind, whether it’s a microservice with a REST API, a command line application or a serverless function such as AWS Lambda. Each of them makes full use of the Kotlin language and all its features, which ensures complete compatibility among all the components of your system.

I hope something here caught your interest and that at least a few of the Kotlin frameworks and libraries I’ve briefly described will turn out to be useful to you. Feel free to dig into the documentation and guides, try them out yourself, choose the ones you find most helpful, give them a shot, and who knows - perhaps they’ll be game changers for your next project?