Kotlin
This tutorial lets you write a Kotlin application and use Koin inject and retrieve your components.
Get the code
Setup
First, check that the koin-core
dependency is added like below:
The application
In our small app we need to have 2 components:
- HelloMessageData - hold data
- HelloService - use and display data from HelloMessageData
- HelloApplication - retrieve and use HelloService
Data holder
Let's create a HelloMessageData
data class to hold our data:
Service
Let's create a service to display our data from HelloMessageData
. Let's write HelloServiceImpl
class and its interface HelloService
:
The application class
To run our HelloService
component, we need to create a runtime component. Let's write a HelloApplication
class and tag it with KoinComponent
interface. This will later allows us to use the by inject()
functions to retrieve our component:
Declaring dependencies
Now, let's assemble HelloMessageData
with HelloService
, with a Koin module:
We declare each component as single
, as singleton instances.
single { HelloMessageData() }
: declare a singleton ofHelloMessageData
instancesingle { HelloServiceImpl(get()) as HelloService }
: BuildHelloServiceImpl
with injected instance ofHelloMessageData
, declared a singleton ofHelloService
.
That's it!
Just start our app from a main
function: