Sobes.tech
Junior

What is Hilt and what is it used for in Android app development?

sobes.tech AI

Answer from AI

Hilt is an opinionated dependency injection library for Android.

Used for:

  • Simplifying dependency injection: Automates the creation and provision of dependencies.
  • Enhancing testability: Facilitates creating test versions of dependencies.
  • Integration with Android components: Initially supports standard Android classes (Activity, Fragment, ViewModel).

Code examples:

// Example of using @HiltAndroidApp for initializing Hilt
import dagger.hilt.android.HiltAndroidApp

@HiltAndroidApp
class MyApplication : Application() {
    // Hilt setup is automatically handled
}
// Example of injecting a dependency into an Activity
import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import dagger.hilt.android.AndroidEntryPoint
import javax.inject.Inject

@AndroidEntryPoint
class MainActivity : AppCompatActivity() {

    @Inject // Hilt injects the MyService dependency
    lateinit var myService: MyService

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

        myService.doSomething()
    }
}
// Dependency interface
interface MyService {
    fun doSomething()
}

// Dependency implementation
class MyServiceImpl @Inject constructor() : MyService { // @Inject indicates how Hilt creates an instance
    override fun doSomething() {
        println("Doing something...")
    }
}
// Module for providing dependencies
import dagger.Binds
import dagger.Module
import dagger.hilt.InstallIn
import dagger.hilt.components.SingletonComponent
import javax.inject.Singleton

@Module
@InstallIn(SingletonComponent::class) // Sets the module in SingletonComponent (application lifetime)
abstract class ServiceModule {

    @Binds // Binds interface to implementation
    @Singleton // Defines the lifetime of the dependency (singleton)
    abstract fun bindMyService(myServiceImpl: MyServiceImpl): MyService
}