• Stars
    star
    1,165
  • Rank 40,073 (Top 0.8 %)
  • Language
    Kotlin
  • License
    Apache License 2.0
  • Created over 5 years ago
  • Updated 5 months ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

Dependency injection lib for kotlin

kotlin-inject

CircleCIMaven Central Sonatype Snapshot

A compile-time dependency injection library for kotlin.

@Component
abstract class AppComponent {
    abstract val repo: Repository

    @Provides
    protected fun jsonParser(): JsonParser = JsonParser()

    protected val RealHttp.bind: Http
        @Provides get() = this
}

interface Http

@Inject
class RealHttp : Http

@Inject
class Api(private val http: Http, private val jsonParser: JsonParser)

@Inject
class Repository(private val api: Api)
val appComponent = AppComponent::class.create()
val repo = appComponent.repo

Download

Using ksp

settings.gradle

pluginManagement {
    repositories {
        gradlePluginPortal()
        mavenCentral()
    }
}

build.gradle

plugins {
    id("org.jetbrains.kotlin.jvm") version "1.9.0"
    id("com.google.devtools.ksp") version "1.9.0-1.0.13"
}

repositories {
    mavenCentral()
    google()
}

dependencies {
    ksp("me.tatarka.inject:kotlin-inject-compiler-ksp:0.6.3")
    implementation("me.tatarka.inject:kotlin-inject-runtime:0.6.3")
}

or with KAPT (deprecated)

plugins {
  id("org.jetbrains.kotlin.jvm") version "1.9.0"
  id("org.jetbrains.kotlin.kapt") version "1.9.0"
}

dependencies {
  kapt("me.tatarka.inject:kotlin-inject-compiler-kapt:0.6.3")
  implementation("me.tatarka.inject:kotlin-inject-runtime:0.6.3")
}

Usage

Let's go through the above example line-by line and see what it's doing.

@Component
abstract class AppComponent {

The building block of kotlin-inject is a component which you declare with an @Component annotation on an abstract class. An implementation of this component will be generated for you.

    abstract val repo: Repository

In your component you can declare abstract read-only properties or functions to return an instance of a given type. This is where the magic happens. kotlin-inject will figure out how to construct that type for you in it's generated implementation. How does it know how to do this? There's a few ways:

@Provides
protected fun jsonParser(): JsonParser = JsonParser()

For external dependencies, you can declare a function or read-only property in the component to create an instance for a certain type. kotlin-inject will use the return type to provide this instance where it is requested.

Note: It is good practice to always explicitly declare the return type, that way it's clear what type is being provided. It may not always be what you expect!

protected val RealHttp.bind: Http
    @Provides get() = this

You can declare arguments to a providing function/property to help you construct your instance. Here we are taking in an instance of RealHttp and providing it for the interface Http. You can see a little sugar with this as the receiver type for an extension function/property counts as an argument. Another way to write this would be:

@Provides
fun http(http: RealHttp): Http = http
@Inject
class RealHttp : Http

@Inject
class Api(private val http: Http, private val jsonParser: JsonParser)

@Inject
class Repository(private val api: Api)

For your own dependencies you can simply annotate the class with @Inject. This will use the primary constructor to create an instance, no other configuration required!

val appComponent = AppComponent::class.create()
val repo = appComponent.repo

Finally, you can create an instance of your component with the generated .create() extension function.

Features

Component Arguments

If you need to pass any instances into your component you can declare them as constructor args. You can then pass them into the generated create function. You can optionally annotate it with @Provides to provide the value to the dependency graph.

@Component
abstract class MyComponent(@get:Provides protected val foo: Foo)
MyComponent::class.create(Foo())

If the argument is another component, you can annotate it with @Component and it's dependencies will also be available to the child component. This allows you to compose them into a graph.

@Component
abstract class ParentComponent {
    protected fun provideFoo(): Foo = ...
}

@Component
abstract class ChildComponent(@Component val parent: ParentComponent) {
    abstract val foo: Foo
}
val parent = ParentComponent::class.create()
val child = ChildComponent::class.create(parent)

Type Alias Support

If you have multiple instances of the same type you want to differentiate, you can use type aliases. They will be treated as separate types for the purposes of injection.

typealias Dep1 = Dep
typealias Dep2 = Dep

@Component
abstract class MyComponent {
    @Provides
    fun dep1(): Dep1 = Dep("one")

    @Provides
    fun dep2(): Dep2 = Dep("two")

    @Provides
    fun provides(dep1: Dep1, dep2: Dep2): Thing = Thing(dep1, dep2)
}

@Inject
class InjectedClass(dep1: Dep1, dep2: Dep2)

Function Injection

You can also use type aliases to inject into top-level functions. Annotate your function with @Inject and create a type alias with the same name.

typealias myFunction = () -> Unit

@Inject
fun myFunction(dep: Dep) {
}

You can then use the type alias anywhere and you will be provided with a function that calls the top-level one with the requested dependencies.

@Inject
class MyClass(val myFunction: myFunction)

@Component
abstract class MyComponent {
    abstract val myFunction: myFunction
}

You can optionally pass explicit args as the last arguments of the function.

typealias myFunction = (String) -> String

@Inject
fun myFunction(dep: Dep, arg: String): String = ...

Scopes

By default kotlin-inject will create a new instance of a dependency each place it's injected. If you want to re-use an instance you can scope it to a component. The instance will live as long as that component does.

First create your scope annotation.

@Scope
@Target(CLASS, FUNCTION, PROPERTY_GETTER)
annotation class MyScope

Then annotate your component with that scope annotation.

@MyScope
@Component
abstract class MyComponent()

Finally, annotate your provides and @Inject classes with that scope.

@MyScope
@Component
abstract class MyComponent {
    @MyScope
    @Provides
    protected fun provideFoo(): Foo = ...
}

@MyScope
@Inject
class Bar()

Component Inheritance

You can define @Provides and scope annotations on an interface or abstract class that's not annotated with @Component. This allows you to have multiple implementations, which is useful for things like testing. For example, you can have an abstract class like

@NetworkScope
abstract class NetworkComponent {
    @NetworkScope
    @Provides
    abstract fun api(): Api
}

Then you can have multiple implementations

@Component
abstract class RealNetworkComponent : NetworkComponent() {
    override fun api(): Api = RealApi()
}

@Component
abstract class TestNetworkComponent : NetworkComponent() {
    override fun api(): Api = FakeApi()
}

Then you can provide the abstract class to your app component

@Component abstract class AppComponent(@Component val network: NetworkComponent)

Then in your app you can do

AppComponent::class.create(RealNetworkComponent::class.create())

and in tests you can do

AppComponent::class.create(TestNetworkComponent::class.create())

Multi-bindings

You can collect multiple bindings into a Map or Set by using the @IntoMap and @IntoSet annotations respectively.

For a set, return the type you want to put into a set, then you can inject or provide a Set<MyType>.

@Component
abstract class MyComponent {
    abstract val allFoos: Set<Foo>

    @IntoSet
    @Provides
    protected fun provideFoo1(): Foo = Foo("1")

    @IntoSet
    @Provides
    protected fun provideFoo2(): Foo = Foo("2")
}

For a map, return a Pair<Key, Value>.

@Component
abstract class MyComponent {
    abstract val fooMap: Map<String, Foo>

    @IntoMap
    @Provides
    protected fun provideFoo1(): Pair<String, Foo> = "1" to Foo("1")

    @IntoMap
    @Provides
    protected fun provideFoo2(): Pair<String, Foo> = "2" to Foo("2")
}

Function Support & Assisted Injection

Sometimes you want to delay the creation of a dependency or provide additional params manually. You can do this by injecting a function that returns the dependency instead of the dependency directly.

The simplest case is you take no args, this gives you a function that can create the dep.

@Inject
class Foo

@Inject
class MyClass(fooCreator: () -> Foo) {
    init {
        val foo = fooCreator()
    }
}

If you define args, you can use these to assist the creation of the dependency. To do so, mark these args with the @Assisted annotation. The function should take the same number of assisted args in the same order.

@Inject
class Foo(bar: Bar, @Assisted arg1: String, @Assisted arg2: String)

@Inject
class MyClass(fooCreator: (arg1: String, arg2: String) -> Foo) {
    init {
        val foo = fooCreator("1", "2")
    }
}

Lazy

Similarly, you can inject a Lazy<MyType> to construct and re-use an instance lazily.

@Inject
class Foo

@Inject
class MyClass(lazyFoo: Lazy<Foo>) {
    val foo by lazyFoo
}

Default Arguments

You can use default arguments for parameters you inject. If the type is present in the graph, it'll be injected, otherwise the default will be used.

@Inject class MyClass(val dep: Dep = Dep("default"))

@Component abstract class ComponentWithDep {
  abstract val myClass: MyClass
  @Provides fun dep(): Dep = Dep("injected")
}
@Component abstract class ComponentWithoutDep {
  abstract val myClass: MyClass
}

ComponentWithDep::class.create().myClass.dep // Dep("injected")
ComponentWithoutDep::class.create().myClass.dep // Dep("default")

Options

You can provide some additional options to the processor.

  • me.tatarka.inject.enableJavaxAnnotations=true

    @javax.inject.* annotations can be used in in addition to the provided annotations. This can be useful if you are migrating existing code or want to be abstracted from the injection lib you are using on the jvm.

  • me.tatarka.inject.generateCompanionExtensions=true

    This will generate the create() methods on the companion object instead of the component's class. This allows you to do MyComponent.create() instead of MyComponent::class.create(). However, due to a kotlin limitation you will have to explicitly specify a companion object for your component.

    @Component abstract class MyComponent {
      companion object
    }
  • me.tatarka.inject.dumpGraph=true

    This will print out the dependency graph when building. This can be useful to help debug issues.

Additional docs

You can find additional docs on specific use-cases in the docs folder.

Samples

You can find various samples here

More Repositories

1

gradle-retrolambda

A gradle plugin for getting java lambda support in java 6, 7 and android
Java
5,315
star
2

binding-collection-adapter

Easy way to bind collections to listviews and recyclerviews with the new Android Data Binding framework
Java
1,911
star
3

JobSchedulerCompat

[Deprecated] A backport of Android Lollipop's JobScheduler to api 10+
Java
735
star
4

rxloader

[Deprecated] Handles Android's activity lifecyle for rxjava's Observable
Java
322
star
5

android-studio-unit-test-plugin

[Deprecated] Android Studio IDE support for Android gradle unit tests. Prepared for Robolectric.
Java
235
star
6

holdr

[Deprecated] Because typing findViewById() in Android is such a pain.
Java
208
star
7

redux

Redux ported to java/android (name tbd)
Java
192
star
8

android-retrolambda-lombok

A modified version of lombok ast that allows lint to run on java 8 sources without error.
Java
175
star
9

compose-collapsable

A generic collapsable implementation with dragging and nested scrolling support
Kotlin
91
star
10

compose-shown

Provides a callback for when a @Composable is shown to the user
Kotlin
65
star
11

injectedvmprovider

Small lib to use easily use Android's ViewModels with a depedency injection framework like dagger
Java
51
star
12

yield-layout

Combine layouts in Android, opposite of how <include/> works.
Java
50
star
13

gsonvalue

Compile-time generation of gson TypeAdapters to preserve class encapsulation
Java
42
star
14

simplefragment

A fragment-like abstraction for Android that is easier to use and understand
Java
41
star
15

streamqflite

flutter reactive stream wrapper around sqflite inspired by sqlbrite
Dart
40
star
16

android-shard

'Fragments' with a simpler api built on top of the android architecture components
Java
29
star
17

studio-splash

An archive of all the Android Studio splash images
Kotlin
26
star
18

timesync

Android library for periodicly syncing data from server.
Java
25
star
19

android-quiznos

Sad about the boring Android 10 naming? This lib give you some options to spice things up.
Java
23
star
20

PokeMVVM

A playground for MVVM style architecture on Android
Java
17
star
21

parsnip

A modern XML library for Android and Java
Java
15
star
22

kotlin-inject-samples

Verious samples using kotlin-inject
Kotlin
15
star
23

android-biometrics-compat-issue

A sample implementation of the androidx biometric compat lib with all the workarounds needed for a production app
Kotlin
15
star
24

loadie

Android Loaders for the rest of us
Java
14
star
25

retain-state

A dead simple way to retain some state thought configuration changes on Android
Java
12
star
26

spanalot

A simple utility for creating and modifying spannables in Android
Java
11
star
27

wiiafl

Wrap it in a FrameLayout
Kotlin
10
star
28

recyclerview-sample

An example of how to use Android L's new RecyclerView with a custom ItemAnimator
Java
10
star
29

voice-changer

Playing around with real-time audio processing on andriod with rust
Kotlin
9
star
30

fragstack

A better android fragment backstack
Kotlin
9
star
31

android-apngrs

Android bindings to image-rs for APNG support.
Kotlin
8
star
32

NyandroidRestorer

Restore our favorite pop-tart-rainbow friend in Android Studio.
Java
7
star
33

android-safe-rxjava-usage

An example of safely using rxjava on Android
Java
7
star
34

nav

A simple declarative Android compose navigator
Kotlin
7
star
35

jackport

Backporting java 8 apis to older versions of android using the jack plugin system.
Java
7
star
36

kotlin-fragment-dsl

A nice kotlin dsl for dealing with the fragment backstack.
Kotlin
7
star
37

sres

Super-Duper Android Layout Preprocessor
Java
6
star
38

assertk

This project has moved to https://github.com/willowtreeapps/assertk
Kotlin
6
star
39

auto-value-lens

AutoValue extension to create lenses for AutoValue properties
Kotlin
5
star
40

flutter_study

Flashcard app written in flutter
Dart
5
star
41

fasax

The fastest way to unmarshall XML to Java on Android
Java
5
star
42

value-processor

Helper for creating annotation processors that create/read value objects.
Kotlin
5
star
43

sparkle

A compiler for FiM++ written in rust
Rust
5
star
44

webpush-fcm-relay

Relays WebPush messages to Firebase Cloud Messaging
Kotlin
5
star
45

typedbundle

Typesafe key-value parinings for Android Bundles.
Java
4
star
46

animated-spans

Playing arround with animating spans in an EditText
Java
4
star
47

silent-support

Backport new android api calls to support lib versions.
Java
4
star
48

FitTextView

Android TextView that scales text to fit area
Java
3
star
49

webpush-encryption

A lightweight webpush encryption/decryption library
Kotlin
3
star
50

kotlin-ir-plugin-example

Playinig around with kotlin ir plugin support added for compose
Kotlin
3
star
51

ipromise

small proimse/future library for java and Android
Java
3
star
52

quickreturn-listview

A quickreturn for a listview in android
Java
3
star
53

yesdata

Errorprone check to verify you have implemented data classes correctly.
Java
3
star
54

domain-mapper

Generates code to map from one domain object to another
Kotlin
3
star
55

kotlin-inject-android

Android extensions to kotlin-inject
Kotlin
2
star
56

named-semaphore

Safe wrapper of libc's named semaphores
Rust
2
star
57

viewpager2stateissue

Kotlin
2
star
58

vimrc

Vim Script
2
star
59

google-actions-wolfram

Query Wolfram Alpha using Google Actions api
JavaScript
2
star
60

gradle-central-release-publishing

An opinionated gradle plugin to manage publishing to maven central
Kotlin
2
star
61

autodata

An extensable alternative to AutoValue.
Java
2
star
62

ponysay-rust

A barebones port of ponysay to rust.
Rust
2
star
63

.emacs.d

My emacs config
JavaScript
2
star
64

RxJavaLeak

A sample project showing a memory leak in RxJava
Java
2
star
65

res

Commandline res manager for android
Rust
2
star
66

fragment-recreator

A utility to handle fragment view-recreation when used in an Activity that handles configuration changes
Kotlin
2
star
67

crequire

A simple way to require c code in ruby using SWIG
Ruby
2
star
68

adp

Android Device Pool
Rust
1
star
69

fragment-view-issue

Kotlin
1
star
70

recyclerview-issue2

Kotlin
1
star
71

android-gradle-jack-plugin

Fork of the android gradle plugin that supports jack plugins
Java
1
star
72

blog

HTML
1
star
73

paging-issue

Kotlin
1
star
74

instance_state

[WIP] Flutter plugin to save/restore instance state on Android
Dart
1
star
75

app-test

Kotlin
1
star
76

android-scroll-to-position-test

Testing how often onBindViewHolder is called when using scrollToPosition() on recyclerview
Java
1
star
77

wordlists

A web application to create and use large lists of words
Ruby
1
star
78

studio-dep-sub-issue

Build failure when using a dependencySubstitution
Java
1
star
79

kotlin-mpp-ui-test

Expirmental cross-platform ui tests with kotlin multiplatform
Swift
1
star
80

placeholder-edittext

Java
1
star
81

prime-multiples

Code for MPMP 19 in rust https://www.think-maths.co.uk/19challenge
Rust
1
star
82

docker-compose-test

A helper to run integration tests with docker-compose
Rust
1
star
83

recyclerview-predraw-issue

Issue with recyclerview animations and predraw listeners
Java
1
star
84

paging-compose-refresh-issue

Kotlin
1
star
85

compose-dialog-window-insets-issue

Kotlin
1
star