Dependency injection with Hilt-1

Yusuf Gültaç
2 min readApr 5, 2021

Before starting, I am going to talk about the purpose of this article. I decided to start this series in order to better understand the technologies I have just learned and to help others. Hopefully, I achieve my goal and take the first step towards a new path to the goal

Outline :

  • Have no time with long initialization processes(it makes automatically)
  • Get rid of writing extra lines of code
  • Initializing objects in the application and also external library objects(Retrofit)
  • Testing code

This technique is called dependency injection. The framework we use for this is called Hilt. Dagger is also used for these operation. However since the Hilt is a new technology, it will gradually replace the dagger.

Let’s check it out!!

Scope :

Before starting code you have to follow the documentation for adding implementations on build.gradle

Hilt operations run in compile time instead of run time. For this reason, when it is done wrong, the application will give an error before opening. For once only create a class and add @HiltAndroidApp and add @AndroidEntrtyPoint to .MainActivity. Finally show it in manifest/application section.

@HiltAndroidApp
class MyApp : Application() {
}
@AndroidEntryPoint
class MainActivity : AppCompatActivity() {
...
<manifest...
<application
android:name=".MyApp"
...

There are two types of injections, which we use both in this example code

  • Constructor injection
  • Field injection
//Constructor injection
class Basketballer
@Inject constructor(position: Position, team: Team) {
fun play(){
println("working...")
}
}

Create classes related main class

//Constructor injection
class Team @Inject constructor() {
}
class Position @Inject constructor() {
}

and identify in MainActivity

class MainActivity : AppCompatActivity() {
//field inject
@Inject
lateinit var jordan: Basketballer
override fun onCreate(...
jordan.play()

Result :

//Logcat
System.out: working...

While working with dependency injection, we need to know about Scopes. We will concentrate on this in the next lesson.

--

--