Getting started with Kotlin

Let’s start with a standalone Kotlin app

Gradle Setup

First, add the Koin dependency like below:

// Add Jcenter to your repositories if needed
repositories {
    jcenter()    
}
dependencies {
    // Koin for Kotlin apps
    compile 'org.koin:koin-core:0.9.3'
}

Declaring our first dependencies

Let’s create a Repository to provide some data (giveHello()):

interface Repository {
    fun giveHello()
}

class MyRepository() : Repository {
    override fun giveHello() = "Hello Koin"
}

A Presenter class, for consuming this data:

// Use Repository - injected by constructor by Koin
class MyPresenter(val repository : Repository){
    fun sayHello() = repository.giveHello()
}

Use the applicationContext function to declare a module. Let’s declare our first component:

// Koin module
val myModule : Module = applicationContext {
    provide { MyPresenter(get()) } // get() will resolve Repository instance
    provide { MyRepository() as Repository }
}

Start Koin

Now that we have a module, let’s start Koin. Open main function, or write one. Just call the startKoin() function:

fun main(vararg args : String){
    // Start Koin
    startKoin(listOf(myModule))
}

That’s it, Koin is running in your app!

Writing the application

To retrieve our MyPresenter component, we need to create a Koin runtime component. Let’s write a MyApplication class, and extend it with KoinComponent interface. This latter allows us to use the by inject() operators:

// Application
class MyApplication : KoinComponent {

    // Inject MyPresenter
    val presenter : MyPresenter by inject()

    init {
        // Let's use our presenter
        Log.i("MyActivity","presenter : ${presenter.sayHello()}")
    }
}

Let’s update our main function, to launch the MyApplication class:

fun main(vararg args : String){
    // Start Koin
    startKoin(this, listOf(myModule))
    // Launch app
    MyApplication()
}

What’s Next?

You have finished this starting tutorial. Below are some topics for further reading: