by inject
- Kotlin course
- Advanced
- Lesson 40/83
- 5 min
Learn to inject dependencies with by inject().
What is by inject?
by inject() is the Koin delegate that gives a class its dependency lazily. It requires the KoinComponent interface.
Example: class App : KoinComponent { val repo: Repository by inject() }. This class gets the Repository instance on first access of repo. Because it is lazy, the dependency is not created until first use. get() can replace inject but it loads eagerly (immediately). by inject() is more efficient.
Practice KoinComponent with by inject
Define class Repository. Define class App : KoinComponent with val repo: Repository by inject() inside. In main, print println("Class ready").
Starter code
// inject delegate
// write here
import org.koin.component.KoinComponent
import org.koin.inject
fun main() {
}Sample solution
class Repository
class App : KoinComponent {
val repo: Repository by inject()
}
fun main() {
println("Class ready")
}Expected output
Class ready
The KoinComponent interface
For a class to use by inject() it must implement the KoinComponent interface. This interface gives the class access to Koin.
Example: class Service : KoinComponent { val repo: Repository by inject() }. Implementing KoinComponent lets the class call get() and inject() inside. This connects the class to Koin directly. Unlike Dagger, Koin has no annotations; you only implement the interface. This approach is idiomatic Kotlin.
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 When does by inject() create the dependency?
- When the class is created
- At app start
- On first access Correct answer
- Never
Explanation: by inject() is lazy, so it creates on first access.
2 Complete the by inject call
class App : KoinComponent {
val repo: Repository ____()
}
class App : KoinComponent {
val repo: Repository by inject()
}
Explanation: by inject() fetches the dependency lazily.
3 Match by inject parts
| Term | Meaning |
|---|---|
by inject |
Lazy delegate |
KoinComponent |
Interface |
Repository |
Dependency |
App |
Class |