Version: 3.2

Kotlin - Annotations

This tutorial lets you write a Kotlin application and use Koin inject and retrieve your components.

Get the code


Add KSP in your root Gradle config:

// Add KSP Plugin
plugins {
id "" version "$ksp_version"

Check that the dependencies are added like below:

// Add Maven Central to your repositories if needed
repositories {
// Use KSP Plugin
apply plugin: ''
// Use KSP Generated sources
sourceSets.main {
dependencies {
// Koin
compile "io.insert-koin:koin-core:$koin_version"
compile "io.insert-koin:koin-annotations:$koin_ksp_version"
ksp "io.insert-koin:koin-ksp-compiler:$koin_ksp_version"

The application

In our small app we need to have components, to make coffee:

  • CoffeeApplication - run the coffee maker
  • CoffeeMaker - run the coffee process, by using a Pump and a Heater
  • ElectricHeater - a electric heater, to heat the water of the coffee
  • Thermosiphon - a pump to pump the water when it's hot

Coffee Maker parts

Below are the components, declared as single instance with @Single annotation:

class ElectricHeater : Heater
class Thermosiphon(private val heater: Heater) : Pump
class CoffeeMaker(private val pump: Pump, private val heater: Heater)

The CoffeeApplication class

To "make our coffee", we need to create a runtime component. Let's write a CoffeeApplication class and tag it with KoinComponent interface. This will later allows us to use the by inject() functions to retrieve our component:

class CoffeeApplication : KoinComponent {
// retrieve CoffeeMaker
private val maker: CoffeeMaker by inject()
fun run(){

Declaring a Module

We just need a module to scan all our components for the given package:

class CoffeeAppModule
  • @Module annotation declare the module class
  • @ComponentScan annotation scan for components

That's it!

Just start our app from a main function:

fun main(vararg args: String) {
startKoin {
// load our module
// run coffee