CodeBlanks Logo Icon CodeBlanks

module

Learn to define modules with module { }.

The module block

A module in Koin is the block where dependencies are declared. It is created with module { ... }.

Example: val appModule = module { single { Repository() } }. This module provides the Repository class as a singleton. Modules are usually assigned to a val and connected with startKoin { modules(appModule) }. A module can hold several dependencies. Modules can be split by app section; e.g. a network module, a database module.

Module structure

Inside a module each dependency is declared with a single or factory block. Dependencies can reference each other directly.

Example: module { single { Repository() }; single { Service(get()) } }. Here Service takes Repository via get(). get() asks Koin for the relevant type. Modules can be written as independent pieces. The startKoin call can take several modules; Koin merges them all.

Practice Define appModule

Define val appModule = module { }. Inside main, print println("Module ready").

Starter code

Main.kt
// module
// write here
import org.koin.dsl.module

fun main() {
    
}

Sample solution

Main.kt
val appModule = module {
}

fun main() {
    println("Module ready")
}

Expected output

Module ready

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Complete the module call

Question
val appModule = ____ {
    single { Repository() }
}
Answer
val appModule = module {
    single { Repository() }
}

Explanation: module opens the dependency block.

2 Match module parts

Term Meaning
module Dependency block
single Singleton
factory New each time
get Another dependency

3 Which is used to get another dependency inside a module?

  • fetch()
  • get() Correct answer
  • find()
  • load()

Explanation: get() fetches another dependency.

All lessons in Advanced