Koin Skill
Comprehensive assistance with koin development, generated from official documentation.
When to Use This Skill
This skill should be triggered when:
- Working with koin
- Asking about koin features or APIs
- Implementing koin solutions
- Debugging koin code
- Learning koin best practices
Quick Reference
Common Patterns
Pattern 1: Koin Annotations InventoryThis document provides a comprehensive inventory of all Koin annotations, their parameters, behaviors, and usage examples.Table of ContentsDefinition Annotations@Single@Factory@ScopedScope Annotations@Scope@ViewModelScope@ActivityScope@ActivityRetainedScope@FragmentScope@ScopeIdViewModel & Android-Specific Annotations@KoinViewModel@KoinWorkerQualifier Annotations@Named@QualifierProperty Annotations@Property@PropertyValueModule & Application Annotations@Module@ComponentScan@Configuration@KoinApplicationMonitoring Annotations@MonitorMeta Annotations (Internal)@ExternalDefinition@MetaDefinition@MetaModule@MetaApplicationDefinition Annotations@SinglePackage: org.koin.core.annotationTarget: CLASS, FUNCTIONDescription: Declares a type or function as a single (singleton) definition in Koin. A single instance is created and shared across the application.Parameters:binds: Array<KClass<>> = [Unit::class] - Explicit types to bind to this definition. Supertypes are automatically detected.createdAtStart: Boolean = false - If true, the instance is created when Koin starts.Behavior: All dependencies are filled by constructor injection.Example:@Singleclass MyClass(val d : MyDependency)Generated Koin DSL:single { MyClass(get()) }With explicit binding:@Single(binds = [MyInterface::class])class MyClass(val d : MyDependency) : MyInterfaceWith creation at start:@Single(createdAtStart = true)class MyClass(val d : MyDependency)@FactoryPackage: org.koin.core.annotationTarget: CLASS, FUNCTIONDescription: Declares a type or function as a factory definition in Koin. A new instance is created each time it is requested.Parameters:binds: Array<KClass<*>> = [Unit::class] - Explicit types to bind to this definition. Supertypes are automatically detected.Behavior: All dependencies are filled by constructor injection. Each request creates a new instance.Example:@Factoryclass MyClass(val d : MyDependency)Generated Koin DSL:factory { MyClass(get()) }@ScopedPackage: org.koin.core.annotationTarget: CLASS, FUNCTIONDescription: Declares a type or function as a scoped definition in Koin. Must be associated with @Scope annotation. Instance is shared within a specific scope.Parameters:binds: Array<KClass<*>> = [Unit::class] - Explicit types to bind to this definition. Supertypes are automatically detected.Behavior: Creates a scoped instance that lives within the defined scope's lifetime.Example:@Scope(MyScope::class)@Scopedclass MyClass(val d : MyDependency)See Also: @ScopeScope Annotations@ScopePackage: org.koin.core.annotationTarget: CLASS, FUNCTIONDescription: Declares a class in a Koin scope. Scope name is described by either value (class) or name (string). By default, declares a scoped definition. Can be overridden with @Scoped, @Factory, @KoinViewModel annotations for explicit bindings.Parameters:value: KClass<*> = Unit::class - Scope class valuename: String = "" - Scope string valueBehavior: Creates a scope definition associated with the specified scope type or name.Example with class:@Scope(MyScope::class)class MyClass(val d : MyDependency)Generated Koin DSL:scope { scoped { MyClass(get()) }}Example with string name:@Scope(name = "my_custom_scope")class MyClass(val d : MyDependency)@ViewModelScopePackage: org.koin.core.annotationTarget: CLASS, FUNCTIONDescription: Declares a class in a ViewModelScope Koin scope. This is a scope archetype for components that should live within a ViewModel's lifecycle.Parameters: NoneBehavior: Creates a scoped definition within the viewModelScope.Example:@ViewModelScopeclass MyClass(val d : MyDependency)Generated Koin DSL:viewModelScope { scoped { MyClass(get()) }}Usage: The tagged class is meant to be used with ViewModel and viewModelScope function to activate the scope.@ActivityScopePackage: org.koin.android.annotationTarget: CLASS, FUNCTIONDescription: Declares a class in an Activity Koin Scope.Parameters: NoneBehavior: Creates a scoped definition within the activityScope.Example:@ActivityScopeclass MyClass(val d : MyDependency)Generated Koin DSL:activityScope { scoped { MyClass(get()) }}Usage: The tagged class is meant to be used with Activity and activityScope function to activate the scope.@ActivityRetainedScopePackage: org.koin.android.annotationTarget: CLASS, FUNCTIONDescription: Declares a class in an Activity Koin scope, but retained across configuration changes.Parameters: NoneBehavior: Creates a scoped definition within the activityRetainedScope.Example:@ActivityRetainedScopeclass MyClass(val d : MyDependency)Generated Koin DSL:activityRetainedScope { scoped { MyClass(get()) }}Usage: The tagged class is meant to be used with Activity and activityRetainedScope function to activate the scope.@FragmentScopePackage: org.koin.android.annotationTarget: CLASS, FUNCTIONDescription: Declares a class in a Fragment Koin scope.Parameters: NoneBehavior: Creates a scoped definition within the fragmentScope.Example:@FragmentScopeclass MyClass(val d : MyDependency)Generated Koin DSL:fragmentScope { scoped { MyClass(get()) }}Usage: The tagged class is meant to be used with Fragment and fragmentScope function to activate the scope.@ScopeIdPackage: org.koin.core.annotationTarget: VALUE_PARAMETERDescription: Annotates a parameter from class constructor or function to request resolution for a given scope with Scope ID.Parameters:value: KClass<*> = Unit::class - Scope typename: String = "" - Scope string identifierBehavior: Resolves the dependency from a specific scope identified by type or name.Example with string name:@Factoryclass MyClass(@ScopeId(name = "my_scope_id") val d : MyDependency)Generated Koin DSL:factory { MyClass(getScope("my_scope_id").get()) }Example with type:@Factoryclass MyClass(@ScopeId(MyScope::class) val d : MyDependency)ViewModel & Android-Specific Annotations@KoinViewModelPackage: org.koin.android.annotationTarget: CLASS, FUNCTIONDescription: ViewModel annotation for Koin definition. Declares a type or function as a viewModel definition in Koin.Platform Support:✅ Android✅ Kotlin Multiplatform (KMP)✅ Compose Multiplatform (CMP)Parameters:binds: Array<KClass<*>> = [] - Explicit types to bind to this definition. Supertypes are automatically detected.Behavior: All dependencies are filled by constructor injection. Creates a ViewModel instance managed by Koin. Works across all platforms including Android, iOS, Desktop, and Web when using Compose Multiplatform.Example (Android/CMP):@KoinViewModelclass MyViewModel(val d : MyDependency) : ViewModel()Example (KMP/CMP shared):@KoinViewModelclass SharedViewModel( val repository: Repository, val analytics: Analytics) : ViewModel()Generated Koin DSL:viewModel { MyViewModel(get()) }@KoinWorkerPackage: org.koin.android.annotationTarget: CLASS, FUNCTIONDescription: Worker annotation for Koin Definition. Declares a type as a worker definition for WorkManager workers.Parameters:binds: Array<KClass<*>> = [] - Explicit types to bind to this definition.Behavior: Creates a worker definition for Android WorkManager integration.Example:@KoinWorkerclass MyWorker() : Worker()Qualifier Annotations@NamedPackage: org.koin.core.annotationTarget: CLASS, FUNCTION, VALUE_PARAMETERDescription: Defines a qualifier for a given definition. Generates StringQualifier("...") or type-based qualifier.Parameters:value: String = "" - String qualifiertype: KClass<*> = Unit::class - Class qualifierBehavior: Used to distinguish between multiple definitions of the same type.Example with string:@Single@Named("special")class MyClass(val d : MyDependency)Usage in parameter:@Singleclass Consumer(@Named("special") val myClass: MyClass)Example with type:@Single@Named(type = MyType::class)class MyClass(val d : MyDependency)@QualifierPackage: org.koin.core.annotationTarget: CLASS, FUNCTION, VALUE_PARAMETERDescription: Defines a qualifier for a given definition. Similar to @Named but with reversed parameter priority.Parameters:value: KClass<*> = Unit::class - Class qualifiername: String = "" - String qualifierBehavior: Used to distinguish between multiple definitions of the same type.Example:@Single@Qualifier(name = "special")class MyClass(val d : MyDependency)Property Annotations@PropertyPackage: org.koin.core.annotationTarget: VALUE_PARAMETERDescription: Annotates a constructor parameter or function parameter to resolve as a Koin property.Parameters:value: String - Property nameBehavior: Resolves the parameter value from Koin properties instead of dependency injection.Example:@Factoryclass MyClass(@Property("name") val name : String)Generated Koin DSL:factory { MyClass(getProperty("name")) }With default value:@PropertyValue("name")val defaultName = "MyName"@Factoryclass MyClass(@Property("name") val name : String)Generated Koin DSL:factory { MyClass(getProperty("name", defaultName)) }@PropertyValuePackage: org.koin.core.annotationTarget: FIELDDescription: Annotates a field value that will be a Property default value.Parameters:value: String - Property nameBehavior: Defines a default value for a property that can be used when the property is not found.Example:@PropertyValue("name")val defaultName = "MyName"@Factoryclass MyClass(@Property("name") val name : String)Generated Koin DSL:factory { MyClass(getProperty("name", defaultName)) }Module & Application Annotations@ModulePackage: org.koin.core.annotationTarget: CLASSDescription: Class annotation to help gather definitions inside a Koin module. Each function can be annotated with a Koin definition annotation.Parameters:includes: Array<KClass<*>> = [] - Module classes to includecreatedAtStart: Boolean = false - If true, module instances are created at startBehavior: Gathers all annotated functions and classes within the module.Example:@Moduleclass MyModule { @Single fun myClass(d : MyDependency) = MyClass(d)}Generated Koin DSL:val MyModule.module = module { val moduleInstance = MyModule() single { moduleInstance.myClass(get()) }}With includes:@Module(includes = [OtherModule::class])class MyModule { // definitions}@ComponentScanPackage: org.koin.core.annotationTarget: CLASS, FIELDDescription: Gathers definitions declared with Koin definition annotations. Scans current package or explicit package names.Parameters:value: vararg String = [] - Packages to scan (supports glob patterns)Behavior: Scans specified packages for annotated classes. Supports both exact package names and glob patterns.Glob Pattern Support:Exact package names (no wildcards):com.example.service - Scans package and all subpackages (equivalent to com.example)Multi-level scan including root:com.example* - Scans com.example and all subpackagesMulti-level scan excluding root:com.example.** - Scans only subpackages of com.example, excludes rootSingle-level wildcard:com.example..service - Matches exactly one level (e.g., com.example.user.service)Combined wildcards:com.**.service.data - Complex pattern matchingcom..service.* - Scans subpackages under patternExample - scan current package:@ComponentScanclass MyAppExample - scan specific packages:@ComponentScan("com.example.services", "com.example.repositories")class MyAppExample - with glob patterns:@ComponentScan("com.example.**", "org.app.*.services")class MyApp@ConfigurationPackage: org.koin.core.annotationTarget: CLASS, FIELDDescription: Applied to @Module class to associate it with one or more configurations (tags/flavors).Parameters:value: vararg String = [] - Configuration namesBehavior: Modules can be grouped into configurations for conditional loading.Default Configuration:@Module@Configurationclass MyModuleThis module is part of the "default" configuration.Multiple Configurations:@Module@Configuration("prod", "test")class MyModuleThis module is available in both "prod" and "test" configurations.With Default:@Module@Configuration("default", "test")class MyModuleAvailable in default and test configurations.Note: @Configuration("default") is equivalent to @Configuration@KoinApplicationPackage: org.koin.core.annotationTarget: CLASSDescription: Tags a class as a Koin application entry point. Generates Koin application bootstrap with startKoin() or koinApplication() functions.Parameters:configurations: Array = [] - List of configuration names to scanmodules: Array<KClass<*>> = [Unit::class] - List of modules to load besides configurationsBehavior: Generates bootstrap functions that scan for configurations and included modules.Example - default configuration:@KoinApplicationclass MyAppGenerated functions:MyApp.startKoin()MyApp.koinApplication()Example - specific configurations:@KoinApplication(configurations = ["default", "prod"])class MyAppExample - with modules:@KoinApplication( configurations = ["default"], modules = [CoreModule::class, ApiModule::class])class MyAppUsage with custom configuration:MyApp.startKoin { printLogger() // additional configuration}Monitoring Annotations@MonitorPackage: org.koin.core.annotationTarget: CLASS, FUNCTIONDescription: Marks a class or function for automatic monitoring and performance tracing through Kotzilla Platform, the official tooling platform for Koin.Parameters: NoneBehavior:When applied to a class: Generates a Koin proxy that monitors all public method callsWhen applied to a function: Monitors that specific method within a Koin-managed componentAutomatically captures performance metrics, error rates, and usage patternsSends data to Kotzilla workspace for real-time analysisRequirements:implementation 'io.kotzilla:kotzilla-core:latest.version'Valid Kotzilla Platform account and API keyExample:@Monitorclass UserService(private val userRepository: UserRepository) { fun findUser(id: String): User? = userRepository.findById(id)}Resources:Kotzilla PlatformComplete DocumentationLatest VersionSince: Kotzilla 1.2.1Meta Annotations (Internal)These annotations are for internal use only by the Koin compiler and code generation.@ExternalDefinitionPackage: org.koin.meta.annotationsTarget: CLASS, FIELD, FUNCTIONDescription: Internal usage for components discovery in generated package.Parameters:value: String = "" - Package of declared definition@MetaDefinitionPackage: org.koin.meta.annotationsTarget: CLASS, FUNCTION, PROPERTYDescription: Meta Definition annotation to help represent definition metadata.Parameters:value: String = "" - Definition full pathmoduleTagId: String = "" - Module Tag + ID (format: "module_id:module_tag")dependencies: Array = [] - Parameters tags to checkbinds: Array = [] - Bound typesqualifier: String = "" - Qualifierscope: String = "" - Scope where it's declared@MetaModulePackage: org.koin.meta.annotationsTarget: CLASSDescription: Meta Module annotation to help represent module metadata.Parameters:value: String = "" - Module full pathid: String = "" - Module IDincludes: Array = [] - Includes Module Tags to checkconfigurations: Array = [] - Module Configurations to checkisObject: Boolean = false - Whether the module is an object@MetaApplicationPackage: org.koin.meta.annotationsTarget: CLASSDescription: Meta Application annotation to help represent application metadata.Parameters:value: String = "" - Application full pathincludes: Array = [] - Used Module Tags to checkconfigurations: Array = [] - Used Configurations modules to checkDeprecated Annotations@SingletonPackage: org.koin.core.annotationStatus: DEPRECATED - ERROR levelReplacement: Use @Singleton from koin-jsr330 package insteadDescription: Same as @Single but deprecated in favor of JSR-330 compliance.Summary TableAnnotationPackagePurposeCommon Use Case@Singleorg.koin.core.annotationSingleton definitionShared application services@Factoryorg.koin.core.annotationFactory definitionPer-request instances@Scopedorg.koin.core.annotationScoped definitionScope-specific instances@Scopeorg.koin.core.annotationScope declarationCustom scopes@ViewModelScopeorg.koin.core.annotationViewModel scopeViewModel-scoped dependencies@ActivityScopeorg.koin.android.annotationActivity scopeActivity-scoped dependencies@ActivityRetainedScopeorg.koin.android.annotationRetained activity scopeConfig-change surviving deps@FragmentScopeorg.koin.android.annotationFragment scopeFragment-scoped dependencies@ScopeIdorg.koin.core.annotationScope resolutionResolve from specific scope@KoinViewModelorg.koin.android.annotationViewModel definitionAndroid/KMP/CMP ViewModels@KoinWorkerorg.koin.android.annotationWorker definitionWorkManager workers@Namedorg.koin.core.annotationString/type qualifierDistinguish same-type beans@Qualifierorg.koin.core.annotationType/string qualifierDistinguish same-type beans@Propertyorg.koin.core.annotationProperty injectionConfiguration values@PropertyValueorg.koin.core.annotationProperty defaultDefault config values@Moduleorg.koin.core.annotationModule declarationGroup definitions@ComponentScanorg.koin.core.annotationPackage scanningAuto-discover definitions@Configurationorg.koin.core.annotationModule configurationBuild variants/flavors@KoinApplicationorg.koin.core.annotationApp entry pointBootstrap Koin@Monitororg.koin.core.annotationPerformance monitoringProduction monitoringDocument Version: 1.0 Last Updated: 20-10-2025 Koin Annotations Version: 2.2.x+
org.koin.core.annotation
Pattern 2: Example:
@Singleclass MyClass(val d : MyDependency)
Pattern 3: Example:
@Factoryclass MyClass(val d : MyDependency)
Pattern 4: Example:
@Scope(MyScope::class)@Scopedclass MyClass(val d : MyDependency)
Pattern 5: Example:
@ViewModelScopeclass MyClass(val d : MyDependency)
Pattern 6: Why Koin?Koin provides an easy and efficient way to incorporate dependency injection into any Kotlin application(Multiplatform, Android, backend ...)The goals of Koin are:Simplify your Dependency Injection infrastructure with smart APIKotlin DSL easy to read, easy to use, to let you write any kind of application Provides different kind of integration from Android ecosystem, to more backend needs like KtorAllow to be used with annotations Koin in a nutshellMaking your Kotlin development easy and productiveKoin is a smart Kotlin dependency injection library to keep you focused on your app, not on your tools.class MyRepository()class MyPresenter(val repository : MyRepository) // just declare it val myModule = module { singleOf(::MyPresenter) singleOf(::MyRepository)}Koin gives you simple tools and API to let you build, assemble Kotlin related technologies into your application and let you scale your business with easiness.fun main() { // Just start Koin startKoin { modules(myModule) }} Ready for AndroidThanks to the Kotlin language, Koin extends the Android platform and provides new features as part of the original platform.class MyApplication : Application() { override fun onCreate() { super.onCreate() startKoin { modules(myModule) } } }Koin provides easy and powerful API to retrieve your dependencies anywhere in Android components, with just using by inject() or by viewModel()class MyActivity : AppCompatActivity() { val myPresenter : MyPresenter by inject()} Powering Kotlin MultiplatformSharing code between mobile platforms is one of the major Kotlin Multiplatform use cases. With Kotlin Multiplatform Mobile, you can build cross-platform mobile applications and share common code between Android and iOS.Koin provides multiplatform dependency injection and help build your components across your native mobile applications, and web/backend applications.Performances and ProductivityKoin is a pure Kotlin framework, designed to be straight forward in terms of usage and execution. It easy to use and doesn't impact your compilation time, nor require any extra plugin configuration.Koin: A Dependency Injection FrameworkKoin is a popular dependency injection (DI) framework for Kotlin, offering a modern and lightweight solution for managing your application’s dependencies with minimal boilerplate code.Dependency Injection vs. Service LocatorWhile Koin may appear similar to a service locator pattern, there are key differences that set it apart:Service Locator: A service locator is essentially a registry of available services where you can request an instance of a service as needed. It is responsible for creating and managing these instances, often using a static, global registry.Dependency Injection: In contrast, Koin is a pure dependency injection framework. With Koin, you declare your dependencies in modules, and Koin handles the creation and wiring of objects. It allows for the creation of multiple, independent modules with their own scopes, making dependency management more modular and avoiding potential conflicts.Koin’s Approach: A Blend of Flexibility and Best PracticesKoin supports both DI and the Service Locator pattern, offering flexibility to developers. However, it strongly encourages the use of DI, particularly constructor injection, where dependencies are passed as constructor parameters. This approach promotes better testability and makes your code easier to reason about.Koin’s design philosophy is centered around simplicity and ease of setup while allowing for complex configurations when necessary. By using Koin, developers can manage dependencies effectively, with DI being the recommended and preferred approach for most scenarios.Transparency and Design OverviewKoin is designed to be a versatile Inversion of Control (IoC) container that supports both Dependency Injection (DI) and Service Locator (SL) patterns. To provide a clear understanding of how Koin operates and to guide you in using it effectively, let’s explore the following aspects:How Koin Balances DI and SLKoin combines elements of both DI and SL, which may influence how you use the framework:Global Context Usage: By default, Koin provides a globally accessible component that acts like a service locator. This allows you to retrieve dependencies from a central registry using KoinComponent or inject functions.Isolated Components: Although Koin encourages the use of Dependency Injection, particularly constructor injection, it also allows for isolated components. This flexibility means you can configure your application to use DI where it makes the most sense while still taking advantage of SL for specific cases.SL in Android Components: In Android development, Koin often uses SL internally within components such as Application and Activity for ease of setup. From this point, Koin recommends DI, especially constructor injection, to manage dependencies in a more structured way. However, this is not enforced, and developers have the flexibility to use SL if needed.Why This Matters to YouUnderstanding the distinction between DI and SL helps in managing your application’s dependencies effectively:Dependency Injection: Encouraged by Koin for its benefits in testability and maintainability. Constructor injection is preferred as it makes dependencies explicit and enhances code clarity.Service Locator: While Koin supports SL for convenience, especially in Android components, relying solely on SL can lead to tighter coupling and reduced testability. Koin’s design provides a balanced approach, allowing you to use SL where it’s practical but promoting DI as the best practice.Making the Most of KoinTo use Koin effectively:Follow Best Practices: Use constructor injection where possible to align with best practices for dependency management. This approach improves testability and maintainability.Leverage Koin’s Flexibility: Utilize Koin’s support for SL in scenarios where it simplifies setup, but aim to rely on DI for managing core application dependencies.Refer to Documentation and Examples: Review Koin’s documentation and examples to understand how to configure and use DI and SL appropriately based on your project needs.Visualize Dependency Management: Diagrams and examples can help illustrate how Koin resolves dependencies and manages them within different contexts. These visual aids can provide a clearer understanding of Koin’s internal workings.By providing this guidance, we aim to help you navigate Koin’s features and design choices effectively, ensuring you can leverage its full potential while adhering to best practices in dependency management.
class MyRepository()class MyPresenter(val repository : MyRepository) // just declare it val myModule = module { singleOf(::MyPresenter) singleOf(::MyRepository)}
Pattern 7: Global Context Usage: By default, Koin provides a globally accessible component that acts like a service locator. This allows you to retrieve dependencies from a central registry using KoinComponent or inject functions.
KoinComponent
Pattern 8: DefinitionsBy using Koin, you describe definitions in modules. In this section we will see how to declare, organize & link your modules.Writing a moduleA Koin module is the space to declare all your components. Use the module function to declare a Koin module:val myModule = module { // your dependencies here}In this module, you can declare components as described below.Defining a singletonDeclaring a singleton component means that Koin container will keep a unique instance of your declared component. Use the single function in a module to declare a singleton:class MyService()val myModule = module { // declare single instance for MyService class single { MyService() }}Defining your component within a lambdasingle, factory & scoped keywords help you declare your components through a lambda expression. this lambda describe the way that you build your component. Usually we instantiate components via their constructors, but you can also use any expression.single { Class constructor // Kotlin expression }The result type of your lambda is the main type of your componentDefining a factoryA factory component declaration is a definition that will provide you a new instance each time you ask for this definition (this instance is not retained by Koin container, as it won't inject this instance in other definitions later). Use the factory function with a lambda expression to build a component.class Controller()val myModule = module { // declare factory instance for Controller class factory { Controller() }}info Koin container doesn't retain factory instances as it will give a new instance each time the definition is asked.Resolving & injecting dependenciesNow that we can declare components definitions, we want to link instances with dependency injection. To resolve an instance in a Koin module, just use the get() function to request the needed component instance. This get() function is usually used into constructor, to inject constructor values.info To make dependency injection with Koin container, we have to write it in constructor injection style: resolve dependencies in class constructors. This way, your instance will be created with injected instances from Koin.Let's take an example with several classes:// Presenter <- Serviceclass Service()class Controller(val view : View)val myModule = module { // declare Service as single instance single { Service() } // declare Controller as single instance, resolving View instance with get() single { Controller(get()) }}Definition: binding an interfaceA single or a factory definition use the type from their given lambda definition i.e: single { T } The matched type of the definition is the only matched type from this expression.Let's take an example with a class and implemented interface:// Service interfaceinterface Service{ fun doSomething()}// Service Implementationclass ServiceImp() : Service { fun doSomething() { ... }}In a Koin module we can use the as cast Kotlin operator as follows:val myModule = module { // Will match type ServiceImp only single { ServiceImp() } // Will match type Service only single { ServiceImp() as Service }}You can also use the inferred type expression:val myModule = module { // Will match type ServiceImp only single { ServiceImp() } // Will match type Service only single { ServiceImp() }}note This 2nd way of style declaration is preferred and will be used for the rest of the documentation.Additional type bindingIn some cases, we want to match several types from just one definition.Let's take an example with a class and interface:// Service interfaceinterface Service{ fun doSomething()}// Service Implementationclass ServiceImp() : Service{ fun doSomething() { ... }}To make a definition bind additional types, we use the bind operator with a class:val myModule = module { // Will match types ServiceImp & Service single { ServiceImp() } bind Service::class}Note here, that we would resolve the Service type directly with get(). But if we have multiple definitions binding Service, we have to use the bind<>() function.Definition: naming & default bindingsYou can specify a name to your definition, to help you distinguish two definitions about the same type:Just request your definition with its name:val myModule = module { single(named("default")) { ServiceImpl() } single(named("test")) { ServiceImpl() }}val service : Service by inject(qualifier = named("default"))get() and by inject() functions let you specify a definition name if needed. This name is a qualifier produced by the named() function.By default, Koin will bind a definition by its type or by its name, if the type is already bound to a definition.val myModule = module { single { ServiceImpl1() } single(named("test")) { ServiceImpl2() }}Then:val service : Service by inject() will trigger the ServiceImpl1 definitionval service : Service by inject(named("test")) will trigger the ServiceImpl2 definitionDeclaring injection parametersIn any definition, you can use injection parameters: parameters that will be injected and used by your definition:class Presenter(val view : View)val myModule = module { single{ (view : View) -> Presenter(view) }}In contrary to resolved dependencies (resolved with get()), injection parameters are parameters passed through the resolution API. This means that those parameters are values passed with get() and by inject(), with the parametersOf function:val presenter : Presenter by inject { parametersOf(view) }Further reading in the Injection Parameters SectionDefinition Termination - OnCloseYou can use the onClose function, to add on a definition, the callback once definition closing is called:class Presenter(val view : View)val myModule = module { factory { (view : View) -> Presenter(view) } onClose { // closing callback - it is Presenter }}Using definition flagsKoin DSL also proposes some flags.Create instances at startA definition or a module can be flagged as CreatedAtStart, to be created at start (or when you want). First set the createdAtStart flag on your module or on your definition.CreatedAtStart flag on a definitionval myModuleA = module { single { ServiceImp() }}val myModuleB = module { // eager creation for this definition single(createdAtStart=true) { TestServiceImp() }}CreatedAtStart flag on a module:val myModuleA = module { single { ServiceImp() }}val myModuleB = module(createdAtStart=true) { single{ TestServiceImp() }}The startKoin function will automatically create definitions instances flagged with createdAtStart.// Start Koin modulesstartKoin { modules(myModuleA,myModuleB)}infoif you need to load some definition at a special time (in a background thread instead of UI for example), just get/inject the desired components.Explicit override per definition (4.2.0+)When you have allowOverride(false) enabled for strict control, but need specific definitions to override existing ones, you can use the .override() option:val productionModule = module { single { ProductionService() }}val testModule = module { // Explicitly mark this definition as allowed to override single { MockService() }.override()}startKoin { allowOverride(false) // Strict mode modules(productionModule, testModule)}You can also use it with withOptions:single { MockService() } withOptions { override()}This is particularly useful for:Test configurations that need to override production servicesFeature flags that conditionally override implementationsPlugin systems where specific plugins can override defaultsSee Modules - Explicit Override for more details.Dealing with genericsKoin definitions doesn't take in accounts generics type argument. For example, the module below tries to define 2 definitions of List:module { single { ArrayList() } single { ArrayList() }}Koin won't start with such definitions, understanding that you want to override one definition for the other.To allow you, use the 2 definitions you will have to differentiate them via their name, or location (module). For example:module { single(named("Ints")) { ArrayList() } single(named("Strings")) { ArrayList() }}
module
Example Code Patterns
Example 1 (kotlin):
@Singleclass MyClass(val d : MyDependency)
Example 2 (kotlin):
single { MyClass(get()) }
Example 3 (kotlin):
// Tag your component to declare a definition@Singleclass MyComponent
Example 4 (kotlin):
// Declare a module and scan for annotations@Moduleclass MyModule
Example 5 (groovy):
dependencies { // Koin for Android implementation("io.insert-koin:koin-android:$koin_version")}
Reference Files
This skill includes comprehensive documentation in references/:
- getting_started.md - Getting Started documentation
Use view to read specific reference files when detailed information is needed.
Working with This Skill
For Beginners
Start with the getting_started or tutorials reference files for foundational concepts.
For Specific Features
Use the appropriate category reference file (api, guides, etc.) for detailed information.
For Code Examples
The quick reference section above contains common patterns extracted from the official docs.
Resources
references/
Organized documentation extracted from official sources. These files contain:
- Detailed explanations
- Code examples with language annotations
- Links to original documentation
- Table of contents for quick navigation
scripts/
Add helper scripts here for common automation tasks.
assets/
Add templates, boilerplate, or example projects here.
Notes
- This skill was automatically generated from official documentation
- Reference files preserve the structure and examples from source docs
- Code examples include language detection for better syntax highlighting
- Quick reference patterns are extracted from common usage examples in the docs
Updating
To refresh this skill with updated documentation:
- Re-run the scraper with the same configuration
- The skill will be rebuilt with the latest information