Summary - DI
- Kotlin course
- Advanced
- Lesson 42/83
- 5 min
Combine module, single and by inject to write a service layer.
Summary - DI
This group covered Koin, module, single and factory, by inject and by viewModel. They are the foundations of dependency injection in Kotlin.
You start with a startKoin call, declare dependencies with module, set lifetime with single/factory, give classes their dependencies with by inject(), and bind ViewModels with by viewModel(). Together they form a loosely coupled app.
Practice Summary: DI
Define val appModule = module { single { Repository() } }. Also define class Repository. In main, call startKoin { modules(appModule) } and print println("Summary ready").
Starter code
// Summary: DI
// write here
import org.koin.core.context.startKoin
import org.koin.dsl.module
fun main() {
}Sample solution
class Repository
val appModule = module {
single { Repository() }
}
fun main() {
startKoin {
modules(appModule)
}
println("Summary ready")
}Expected output
Summary ready
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Which declares a singleton dependency?
- single Correct answer
- factory
- module
- get
Explanation: single declares a singleton.
2 Match all DI concepts
| Term | Meaning |
|---|---|
startKoin |
Startup |
module |
Dependency block |
single |
Singleton |
by inject |
Lazy dependency |
by viewModel |
ViewModel |