Dependency injection with Hilt-2(Scope)

Yusuf Gültaç
2 min readApr 5, 2021

Outline :

Each class has its own scopes. If we work with more than one class, scope will help us. However there is a hierarchy we have to follow in order to use Scopes.

A scoped binding will only be created once per instance of the component it’s scoped to, and all requests for that binding will share the same instance.

So let’s check it out.

The table below lists scope annotations for each generated component:

https://developer.android.com/training/dependency-injection/hilt-android

Scope gets narrower from top to bottom.

Scope :

In this example we use @ActivityScoped, That’s why we should use scope narrower than activity class.

@ActivityScoped
class Basketballer
@Inject
constructor(position: Position, team: Team) {
fun play(){
println("working...")
}
}

Create a sample fragment in .MainActivity an test it.

@AndroidEntryPoint
class FragmentExample(): Fragment(){
@Inject
lateinit var lebron : Basketballer
}

Result :

Scoping a binding has a cost on both the generated code size and its runtime performance so use scoping sparingly.

In the next article, We will dip into the module.

--

--