Kotlin
Completed
-
Section 1: Getting Started
-
Section 2: Core Syntax
-
Section 3: Null Safety
-
Section 4: Object-Oriented Kotlin
-
Section 5: Functional Kotlin
-
Section 6: Coroutines
-
Section 7: Collections Deep Dive
-
Section 8: Type System Deep Dive
-
Section 9: Interop and Tooling
-
Section 10: Kotlin DSLs and Patterns
-
Section 11: Testing and Quality
-
Section 12: Server-Side Kotlin
-
Section 13: Practical Projects
-
Section 14: Interview Practice
-
Section 15: More Practice Exercises
-
Section 16: More Standard Library
-
Section 17: Multiplatform Kotlin
-
Section 18: kotlin.collections In Depth
-
Section 19: kotlin.text In Depth
-
Section 20: kotlin.ranges and kotlin.sequences
-
Section 21: kotlin.io and File Handling
-
Section 22: kotlinx.coroutines Deep Dive
-
Section 23: kotlin.reflect
-
Section 24: Android Development with Kotlin Overview
-
Section 25: Kotlin Multiplatform Deep Dive
-
Section 26: Kotlin for Backend Deep Dive
-
Section 27: Kotlin Design Patterns
-
Section 28: Advanced Language Features
-
Section 29: More Practice Exercises
-
Section 30: More Interview Practice
-
Section 31: Kotlin Type System Deep Dive
-
Section 32: Kotlin Null Safety Advanced
-
Section 33: Kotlin Testing Deep Dive
-
Section 34: Kotlin Build Tooling Deep Dive
-
Section 35: Kotlin Serialization
-
Section 36: Kotlin Performance Considerations
-
Section 37: Kotlin Native Overview
-
Section 38: Kotlin for Data and Scripting
-
Section 39: More Coroutines Practice
-
Section 40: More Android-Adjacent Patterns
-
Section 41: More Practical Projects
-
Section 42: More Design and Architecture Practice
-
Section 43: Kotlin Language Evolution
-
Section 44: More Interview and Review
-
Section 45: Kotlin Delegation Patterns Deep Dive
-
Section 46: Kotlin Annotations Deep Dive
-
Section 47: Kotlin for Gradle Plugin Development
-
Section 48: Kotlin Concurrency Beyond Coroutines
-
Section 49: Kotlin Compiler Internals
-
Section 50: Real-World Kotlin Case Studies
-
Section 51: Final Practice Projects
-
Section 52: Kotlin for Server-Side Reactive Programming
-
Section 53: More Practice and Drills
-
Section 54: Kotlin Security Practices
126: Dependency Injection with Koin
You've probably heard the term "Dependency Injection" (DI) thrown around a thousand times. In a lot of tutorials, it's presented as this complex architectural requirement, often involving massive libraries like Dagger or Hilt that generate mountains of code you can't even see. But at its core, DI is just a fancy way of saying: "Don't let your classes create their own dependencies; give them what they need from the outside."
The Hard-Coded Trap
Let's look at a scenario we've all been in. Imagine you're building a feature to fetch user profiles. You have a UserRepository that needs a UserApi to make network calls and a UserDao to cache data locally. The naive way to do this is to instantiate those dependencies right inside the repository:
class UserRepository {
private val api = UserApi()
private val dao = UserDao()
fun getUser(id: String): User {
return dao.getCachedUser(id) ?: api.fetchUser(id).also { dao.save(it) }
}
}
On the surface, this is clean. It just works. But you've just painted yourself into a corner. If you want to write a unit test for UserRepository, you can't. Why? Because every time you create a UserRepository, it spins up a real UserApi that tries to hit a real server. You can't swap it for a mock or a fake without changing the actual source code of the class. You've "hard-wired" your logic to your infrastructure.
The Manual Plumbing Headache
The next step is usually manual constructor injection. You move the dependencies to the constructor, which is a huge win for testing:
class UserRepository(private val api: UserApi, private val dao: UserDao) {
// logic remains the same
}
Now your tests are easy—you just pass in a mock API. But now you've moved the problem. Instead of the UserRepository creating its dependencies, the ViewModel (or whatever calls the repository) has to do it. Then the Activity has to create the ViewModel. Suddenly, your app's entry point looks like a giant shopping list of object instantiations: val repo = UserRepository(UserApi(), UserDao()). As your app grows to 50 classes, this "manual plumbing" becomes a nightmare. You'll spend half your day just trying to figure out the order in which objects need to be created.
Letting Koin Handle the Graph
This is where Koin comes in. I like Koin because it's a "pragmatic" DI framework. It doesn't use annotation processing or code generation; it's just a DSL (Domain Specific Language) that lets you describe how your objects should be created. You define a module, and Koin keeps a map of how to provide those instances.
Here is how we'd translate our user feature into Koin:
val appModule = module {
single { UserApi() }
single { UserDao() }
single { UserRepository(get(), get()) }
}
Notice the get() function. This is Koin's magic. It tells Koin: "Look at the constructor of UserRepository, see that it needs a UserApi and a UserDao, and go find the definitions for those in your map." single creates a singleton, meaning the same instance is reused throughout the app's lifetime. If you wanted a fresh instance every time, you'd use factory instead.
The Trade-off: Runtime vs. Compile Time
I should be honest with you about the cost. Because Koin is a service locator under the hood and doesn't generate code at compile time, it can't tell you if you've forgotten to define a dependency until the app actually runs. If you call get() for a class you didn't put in a module, your app will crash with a NoBeanDefFoundException.
In a massive enterprise project with hundreds of developers, some people prefer Dagger because it catches these errors when you hit "Build." But for the vast majority of Kotlin projects, the simplicity of Koin—the lack of boilerplate and the incredibly fast build times—far outweighs the risk of a runtime crash that you would have caught in a basic smoke test anyway.
To use these dependencies in your classes, you just implement the KoinComponent interface and use inject(), which lazily retrieves the dependency the first time it's accessed:
class UserViewModel : KoinComponent {
private val repository: UserRepository by inject()
fun loadUser(id: String) {
val user = repository.getUser(id)
// update UI
}
}📋 Practical Task
Refactor the Payment Processing System
You have been handed a legacy PaymentService that is currently hard-coded and impossible to test. Your task is to refactor this into a Koin-managed system.
The Current Code:
class StripeGateway {
fun process(amount: Double) = println("Processing \$$amount via Stripe")
}
class PaymentLogger {
fun log(message: String) = println("LOG: $message")
}
class PaymentService {
private val gateway = StripeGateway()
private val logger = PaymentLogger()
fun executePayment(amount: Double) {
logger.log("Attempting payment of $amount")
gateway.process(amount)
}
}
Requirements:
- Refactor
PaymentServiceto use constructor injection forStripeGatewayandPaymentLogger. - Create a Koin
modulenamedpaymentModulethat provides singletons for all three classes. - Ensure
PaymentServiceis resolved using Koin'sget()function within the module. - Demonstrate how you would instantiate
PaymentServicein a separate class (e.g.,CheckoutController) using theby inject()delegate.
There are no comments for now.