This is part 4 of a series on Dagger. Dagger has a steep learning curve that frequently leaves developers not wanting to explore it further once they've integrated it. This series attempts to show some neat "party tricks" and other clever Dagger patterns to inspire more advanced usage.


This one's a short one! Extension functions are a powerful feature in Kotlin, but did you know you can use them in Dagger?

Remember: Dagger sees your code as if it's plain Java, even if you've written it in Kotlin. Sometimes it's a nuisance, but extension functions are way that Dagger code actually becomes simpler in Kotlin.

Consider this Java code:

@Binds
abstract Taco bindTaco(TacoImpl tacoImpl);

Pretty standard binding in Dagger. This is also the textbook example of an extension function

@Binds
abstract fun TacoImpl.bindTaco(): Taco

Does it work? Yes! Why wouldn't it? Under the hood it's the same as the first one ๐Ÿ™ƒ.

This works for @Provides too

@IsLowRam
@Provides
fun ActivityManager.isLowRam() = isLowRamDevice()

Or extension properties. Particularly useful on interfaces, though I'm admittedly really a fan of this approach.

@Module
interface AppActionsModule {
  @get:Binds
  val TacoImpl.bindTaco: Taco
}

Lastly - what if your receiver is qualified? Easy, annotate it like any other receiver.

@Binds
abstract fun @receiver:YourQualifier TacoImpl.bindTaco(): Taco

Happy binding!