Dagger in kotlin

Dagger in Kotlin

In object oriented design, the dependency inversion principle is a specific form of decoupling software modules.
Abstractions should not depend on details. Details (concrete implementations) should depend on abstractions.
The idea behind points A and B of this principle is that when designing the interaction between a high-level module and a low-level one, the interaction should be thought of as an abstract interaction between them. This not only has implications on the design of the high-level module, but also on the low-level one: the low-level one should be designed with the interaction in mind and it may be necessary to change its usage interface.

Dagger in kotlin
In Android we have Dagger is tool to do dependency inversion.

You can see a example in GitHub

We learn with a simple dagger example in Kotlin:

We have a car

class Car() {

    lateinit var engine: Engine
    lateinit var wheels: Wheels

    @Inject
    constructor(
        engine: Engine,
        wheels: Wheels
    ) : this() {
        this.engine = engine
        this.wheels = wheels

    }

    fun drive():String {
        return "driving..."
    }
}

We can build this car with engine

class Engine @Inject
internal constructor()

and wheels

class Wheels@Inject
internal constructor()

With this to object We can create a object of car. To create a object in Dagger we have to create a interface component:

@Component
interface CarComponent {

    var car:Car
}

And now in our MainActivity, We can use our object:

class MainActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        val carComponent:CarComponent = DaggerCarComponent.create()

        text_view.text = carComponent.car.drive()

    }
}

You can see a example in GitHub