We have Dagger2. Then why Koin?.

Nikhil Seban
3 min readApr 21, 2020

In Android programming, handling dependency is a big concern. For the past few years, we are mainly using Dagger2 for the dependency injection. There is no doubt Dagger2 is one of the best available dependency injection framework now available. Now you can ask, as of now we have Dagger2 then why do we need to think about another framework?

Before knowing the answer to the question, let’s understand what is Dagger2 and Koin.

Simply speaking... Dagger 2 is a dependency injection framework. It is based on the Java Specification Request (JSR) 330. It uses code generation and is based on annotations.

Dagger 2 uses the following annotations:

  • @Module and @Provides: define classes and methods which provide dependencies.
  • @Inject: request dependencies. Can be used on a constructor, a field, or a method.
  • @Component: enable selected modules and used for performing dependency injection

Dagger 2 uses generated code to access the fields and not reflection. Therefore it is not allowed to use private fields for field injection.

Koin is a practically sensible and realistically lightweight dependency injection framework for Kotlin developers. Written in pure Kotlin using functional resolution only: no proxy, no code generation, no reflection!

Koin is a Domain Specific Language, a lightweight container and a pragmatic API.

From the above statements, it is very clear both have the same functional requirements but the differences are very few isn’t it? To make it simple let's go through simple real statistics which I observe.

Lines of code before and after compile.
Build statics.
Google Search statics.

From the above statistical observations, it is very clear koin gains more points over Dagger2. Also from a developer perspective, I really do prefer koin more than Dagger2. Because implementing Dagger2 is a painstaking effort and moreover the debugging of Dagger2 (Ohh…) you will struggle. It may be a small issue, but because of the generated code, it will be a nightmare to fix it. And also learning Dagger2 is hard, so if someone joins your project or team he/she has to spend a lot of time on learning Dagger2.

Okay now, let's answer why Koin?

  1. No Reflection.
  2. No Code generation.
  3. No need to write a lot of code just to do a simple injection.
  4. Very easy to integrate and maintain.
  5. Proxy free.
  6. No boilerplate code.
  7. Testing with Koin is very easy.

How to use Koin?

Just add this line to your Gradle.

// Stable Koin Version
koin_version = "2.1.5"
repositories {
jcenter()
}
dependencies {
// Koin for Android
compile "org.koin:koin-android:$koin_version"
// or Koin for Lifecycle scoping
compile "org.koin:koin-android-scope:$koin_version"
// or Koin for Android Architecture ViewModel
compile "org.koin:koin-android-viewmodel:$koin_version"
}

And create your module file, Go On... Happy Coding,

To be continued... Stay tuned.

For reference on Koin.

--

--