Effective Kotlin: Item 5 — Prefer dependency injection to hardwiring resources

Joshua details the reasons why dependency injection matters in his book Effective Java and although not covered in detail mentions the use of some famous frameworks to tidy up the “clutter” of doing dependency injection yourself.

Implementing dependency injection by hand in Kotlin is no different than in Java, for example with the dependencies passed in through the constructor or setters of your objects.

Using a framework can keep your code clean and easier to maintain. Java-based frameworks include Dagger and Guice, and although there are some wrappers available to make these fit Kotlin better, such as kotlin-guice, they typically don’t feel quite right. Java libraries with Kotlin. The case of dependency injection frameworks is an interesting article showing some techniques that can be used to make the Toothpick library more Kotlin-esque.

There are of course some Kotlin specific dependency injection frameworks with the two most popular currently being Kodein with good interoperability with Java and my personal favourite Koin which has one of the cleanest interfaces. Kotlin is Awesome! documents some other options although none in active development anymore.

You have to research the solution that is right for you as this is not a thorough analysis of the pros and cons of each tool, especially where some would argue that the Kotlin libraries are not real dependency injection frameworks and merely service locators.

Each week I am looking at “items” from Joshua Bloch’s well-respected book, Effective Java to see how it applies to Kotlin. You can find the rest of the items I’ve covered at Effective Kotlin. Please let me know your thoughts.

Matt Dolan has been eating doughnuts and developing with Android since the dark days of v1.6.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store