Use DI even in your spike projects.

All of us create spike projects with only one or two classes in order to test a new functionality. In those case we tend to avoid using Dagger 2 because it takes too long to make its initial configuration.

Some mates have commented me that Dagger 2 is too complex and it doesn’t make sense to include it in small Kotlin projects cause Kotlin’s powerful constructors.

But, what if we could use JSR330 annotations with only a 4 lines interface configuration?

@Component

interface DiComponent {

fun inject(activity: MainActivity)

}

This is all we need to use Dagger 2 DI in our Main Activity:

class MainActivity : AppCompatActivity() {



@Inject

lateinit var presenter: Presenter



override fun onCreate(savedInstanceState: Bundle?) {

super.onCreate(savedInstanceState)

setContentView(R.layout.activity_main)



DaggerDiComponent.create().inject(this)



Log.d("MainActivity", presenter.greet())

}

}

MainActivity will instantiate the component without needing to extend Application, and then inject the Presenter, that in turn could injects its own collaborators if needed or declare an “@Inject” annotated empty constructor.

class Presenter @Inject constructor() {

fun greet() = "Hello World"

}

Of course, don’t forget to add Gradle dependencies to your app build.Gradle:

kapt 'com.google.dagger:dagger-compiler:2.11'

compile 'com.google.dagger:dagger:2.11'

That’s all. This has been a short post but hope I’ve helped you to always use DI, even in pico projects.