Koin as an alternative
Why it matters
- Interviews often ask you to compare compile-time DI (Hilt) with runtime DI (Koin), and to do it fairly.
- Koin is a common choice for Kotlin Multiplatform (KMP) projects, because Hilt is Android-only.
- Koin's graph is checked only when it runs, so a missing definition can ship unless you add a check; knowing the check is part of using Koin well.
- Plenty of production apps use Koin, so you may join a codebase that does.
The simple explanation
- A restaurant with a fixed menu (Hilt): the kitchen checks every recipe against the pantry before opening. A missing ingredient stops the restaurant from opening (a build error).
- A restaurant that cooks to order (Koin): the waiter checks the pantry when you order. A missing ingredient is found at your table (a runtime error), unless someone walked through every recipe before service (a
verify()test).
Hilt generates its graph with an annotation processor at build time. Koin builds its graph at runtime: you describe definitions in a Kotlin DSL, startKoin loads them into a container, and each get() resolves a type when it is called. There is no code generation in the classic DSL.
Koin is usually described as a DI framework; internally its container is a registry looked up at runtime, much like a service locator. Your classes still use constructor injection as long as only the module definitions call get(). Calling get() or inject() inside ordinary classes turns it into service-locator code.
| Hilt | Koin (classic DSL) | |
|---|---|---|
| Graph built | At build time, by KSP (or kapt) | At runtime, from a Kotlin DSL |
| Missing definition | Build error | NoDefinitionFoundException when first resolved, unless a verify() test or compile-time plugin catches it |
| Kotlin Multiplatform | Android only | Shared code for Android, iOS, desktop, server |
| Android integration | @AndroidEntryPoint, @HiltViewModel, @HiltWorker | androidContext, viewModel, koinViewModel(), KoinWorkerFactory |
Definitions (Koin 4):
single { Api(get()) }orsingleOf(::Api): one instance per Koin container, created on first use.factory { Mapper() }orfactoryOf(::Mapper): a new instance every time it is resolved.viewModel { DetailViewModel(get()) }orviewModelOf(::DetailViewModel): aViewModelthat is stored in the caller'sViewModelStoreOwner, so it survives rotation like any ViewModel.scope<MyActivity> { scoped { ... } }: an instance tied to a custom scope, such as an Activity's lifetime.bind<Interface>()(orsingle<Interface> { Impl() }) exposes an implementation as its interface.
Setup. In Application.onCreate() call startKoin { androidLogger(); androidContext(this@App); modules(appModule) }. In Compose, koinViewModel() obtains a ViewModel; in an Activity or Fragment, by viewModel() and by inject().
Checking the graph. appModule.verify() from koin-test (marked experimental) checks in a JVM unit test that every constructor parameter of every definition has a definition. checkModules() is deprecated since Koin 4.0. Koin Annotations (KSP) and the newer Koin compiler plugin can check the graph at build time if you need that.
Notes
- Koin resolves dependencies at runtime. A missing definition throws
NoDefinitionFoundExceptionthe first time that type is resolved, which may be deep inside a screen users rarely open. singleis one instance per Koin container (per process in a normal app). Use it for expensive or shared objects: an HTTP client, a database, a repository with a cache.factorygives a new instance on every resolution. Use it for cheap, stateless objects.viewModel/viewModelOfdeclare ViewModels;koinViewModel()(Compose) andby viewModel()(Activity, Fragment) obtain them from the rightViewModelStoreOwner. ASavedStateHandleconstructor parameter is supplied automatically.- Values only the caller knows are passed with
parametersOf(...)and read in the definition, for exampleviewModel { (id: String) -> DetailViewModel(id, get()) }. - Keep
get()inside module definitions. A class that callsget()orinject()itself hides its dependencies and is harder to test. - Add a
verify()test (or Koin Annotations / the compiler plugin) so missing definitions fail CI instead of crashing users. Types Koin supplies at runtime, likeContextorSavedStateHandle, are passed toverify(extraTypes = ...). - In tests that call
startKoin, callstopKoin()afterwards (or useKoinTestRule); otherwise the next test fails with "A Koin Application has already been started". - Koin works in KMP shared code, which is the main reason KMP projects pick it. Hilt has no iOS or desktop support.
Code example
A Koin setup for an Android app: a module with single, factory and viewModelOf, startKoin in the Application, a Composable that gets the ViewModel, and a test that verifies the module.
// AppModule.kt
import androidx.lifecycle.SavedStateHandle
import androidx.lifecycle.ViewModel
import org.koin.core.module.dsl.bind
import org.koin.core.module.dsl.factoryOf
import org.koin.core.module.dsl.singleOf
import org.koin.core.module.dsl.viewModelOf
import org.koin.dsl.module
interface Analytics { fun log(event: String) }
class LogcatAnalytics : Analytics {
override fun log(event: String) { android.util.Log.d("Analytics", event) }
}
class DateFormatter { fun format(millis: Long): String = java.time.Instant.ofEpochMilli(millis).toString() }
class UserRepository(private val analytics: Analytics) {
fun login(name: String): String { analytics.log("login"); return name }
}
class LoginViewModel(
private val repository: UserRepository,
private val formatter: DateFormatter,
private val savedState: SavedStateHandle, // supplied by Koin
) : ViewModel() {
fun login(name: String) = repository.login(name)
}
val appModule = module {
singleOf(::LogcatAnalytics) { bind<Analytics>() } // one instance, exposed as the interface
singleOf(::UserRepository)
factoryOf(::DateFormatter) // new instance each time
viewModelOf(::LoginViewModel)
}
// App.kt (registered in the manifest)
import android.app.Application
import org.koin.android.ext.koin.androidContext
import org.koin.android.ext.koin.androidLogger
import org.koin.core.context.startKoin
class App : Application() {
override fun onCreate() {
super.onCreate()
startKoin {
androidLogger()
androidContext(this@App)
modules(appModule)
}
}
}
// LoginScreen.kt
import androidx.compose.runtime.Composable
import org.koin.compose.viewmodel.koinViewModel
@Composable
fun LoginScreen(viewModel: LoginViewModel = koinViewModel()) {
// ...
}
// AppModuleTest.kt (src/test, koin-test)
import androidx.lifecycle.SavedStateHandle
import org.koin.core.annotation.KoinExperimentalAPI
import org.koin.test.verify.verify
import kotlin.test.Test
class AppModuleTest {
@OptIn(KoinExperimentalAPI::class)
@Test
fun appModuleIsComplete() {
appModule.verify(extraTypes = listOf(SavedStateHandle::class))
}
}singleOf(::UserRepository)reads the constructor and resolvesAnalyticswithget()for you;single { UserRepository(get()) }is the same definition written by hand.bind<Analytics>()letsUserRepositoryask for the interface. Without it,Analyticswould have no definition andverify()would fail.koinViewModel()comes fromkoin-compose-viewmodel; it stores the ViewModel in the currentViewModelStoreOwner, so rotation returns the same instance.- If someone deletes
factoryOf(::DateFormatter), the app still compiles and crashes when the login screen opens. Theverify()test fails in CI instead.
Run the idea in plain Kotlin
A tiny runtime container in the spirit of Koin: definitions are lambdas stored in a map, single caches, factory does not, and a missing definition only fails when something asks for it.
import kotlin.reflect.KClass
class NoDefinitionFound(type: String) : Exception("No definition found for " + type)
class Container {
private val factories = mutableMapOf<KClass<*>, () -> Any>()
private val singles = mutableMapOf<KClass<*>, Any>()
fun <T : Any> single(type: KClass<T>, create: Container.() -> T) {
factories[type] = { singles.getOrPut(type) { create() } }
}
fun <T : Any> factory(type: KClass<T>, create: Container.() -> T) {
factories[type] = { create() }
}
@Suppress("UNCHECKED_CAST")
fun <T : Any> get(type: KClass<T>): T =
(factories[type] ?: throw NoDefinitionFound(type.simpleName ?: "?")).invoke() as T
}
inline fun <reified T : Any> Container.get(): T = get(T::class)
class HttpClient
class Formatter
class Repo(val client: HttpClient, val formatter: Formatter)
class Settings(val repo: Repo)
fun main() {
val koin = Container()
// module { single { HttpClient() }; factory { Formatter() }; factory { Repo(get(), get()) } }
koin.single(HttpClient::class) { HttpClient() }
koin.factory(Formatter::class) { Formatter() }
koin.factory(Repo::class) { Repo(get(), get()) }
val a = koin.get<Repo>()
val b = koin.get<Repo>()
println("single shared: " + (a.client === b.client))
println("factory shared: " + (a.formatter === b.formatter))
// Settings was never declared: nothing fails until it is requested
println("startup finished")
try {
koin.get<Settings>()
} catch (e: NoDefinitionFound) {
println("crash when Settings opens: " + e.message)
}
}Expected output:
single shared: true
factory shared: false
startup finished
crash when Settings opens: No definition found for Settings
In production
- Crash reports spiked on the Settings screen after a release; the stack trace ended in
NoDefinitionFoundExceptionforSettingsRepository. - A developer had added
SettingsRepositoryas a constructor parameter ofSettingsViewModelbut never declared it in a module. - The app compiled and every other screen worked, so manual QA, which did not open Settings, missed it.
- They added
singleOf(::SettingsRepository)to the data module and shipped a hotfix. - They added a JVM unit test that calls
verify()on every Koin module, so a definition whose constructor needs an undeclared type fails CI. - New ViewModels are declared with
viewModelOf(::X)instead of hand-written lambdas, so the constructor and the definition cannot drift apart.
- After adding Koin, unit tests passed one at a time but failed in a full run with "A Koin Application has already been started".
- Each test class called
startKoinin@Beforeand never stopped it, so the global context from one test was still there in the next.
- Test classes now use
KoinTestRule.create { modules(testModule) }, which starts Koin before each test and stops it after. - ViewModel and repository unit tests stopped using Koin at all: they call constructors with fakes, which is faster and needs no global state.
Common mistakes
- No verify() test. Without one, a missing definition is found by users. Add a
verify()test per module, or use Koin Annotations / the compiler plugin for build-time checks. - Calling get() or inject() inside ordinary classes. The class now pulls from a global container, its constructor no longer shows what it needs, and tests must start Koin. Pass dependencies through the constructor and keep
get()in module definitions. - Using single for everything. Every
singlelives as long as the container and shares its state with every caller. Usefactoryfor cheap, stateless objects andsinglefor expensive or intentionally shared ones. - Declaring a ViewModel with single or factory. It is then not stored in a
ViewModelStoreOwner:factorycreates a new instance on every recomposition or rotation, andsingleshares one forever. UseviewModel/viewModelOf. - Forgetting stopKoin() between tests. The next
startKointhrows because a Koin application is already running. UseKoinTestRuleor callstopKoin()in@After.
Interview questions
Answer out loud first. Then reveal the answer and compare it at each depth.
“What is the difference between Hilt and Koin?”
“Is Koin a dependency injection framework or a service locator?”
“How do you handle object lifetimes in Koin?”
“How do you make sure a Koin configuration is complete?”
Quiz
Which Koin definition creates a new instance every time the type is resolved?
A class is used in a constructor but has no Koin definition. When does the problem show up?
How should a ViewModel be declared in a Koin 4 module?
Which is the current way to check a Koin module in a unit test?
0 of 4 answered
Mini task
Task: Implement and verify a Koin module
- Create an interface
ApiServicewithfun fetchData(): String, andRealApiServicethat returns"Data from API". - Create
class DataRepository(private val api: ApiService)withfun load(): String = api.fetchData(). - Write
val appModule = module { singleOf(::RealApiService) { bind<ApiService>() }; factoryOf(::DataRepository) }. - In a
mainfunction, callstartKoin { modules(appModule) }, get the repository withKoinPlatform.getKoin().get<DataRepository>(), printload(), then callstopKoin(). - Write a JUnit test that calls
appModule.verify(). Then remove thebind<ApiService>()part and run the test again.
Done condition: main prints Data from API, the verify test passes with the full module, and it fails with a message naming ApiService once the binding is removed.