I am a beginner with Kotlin and I am following a tutorial that uses Hilt for dependency injection. Even though the tutorial is from 2023, the lines of code used there no longer work for me; I could not find clear instructions on the internet on what to add to which file.
My current version of Kotlin is 232-1.9.0-release-358-AS10227.8.2321.11479570
If it helps, here is what my current build.gradle (Module: app) looks like:
plugins {
alias(libs.plugins.androidApplication)
alias(libs.plugins.jetbrainsKotlinAndroid)
}
android {
namespace = "com.package.myApp"
compileSdk = 34
defaultConfig {
applicationId = "com.package.myApp"
minSdk = 30
targetSdk = 34
versionCode = 1
versionName = "1.0"
testInstrumentationRunner = "androidx.test.runner.AndroidJUnitRunner"
vectorDrawables {
useSupportLibrary = true
}
}
buildTypes {
release {
isMinifyEnabled = false
proguardFiles(
getDefaultProguardFile("proguard-android-optimize.txt"),
"proguard-rules.pro"
)
}
}
compileOptions {
sourceCompatibility = JavaVersion.VERSION_1_8
targetCompatibility = JavaVersion.VERSION_1_8
}
kotlinOptions {
jvmTarget = "1.8"
}
buildFeatures {
compose = true
}
composeOptions {
kotlinCompilerExtensionVersion = "1.5.1"
}
packaging {
resources {
excludes += "/META-INF/{AL2.0,LGPL2.1}"
}
}
}
dependencies {
implementation(libs.androidx.core.ktx)
implementation(libs.androidx.lifecycle.runtime.ktx)
implementation(libs.androidx.activity.compose)
implementation(platform(libs.androidx.compose.bom))
implementation(libs.androidx.ui)
implementation(libs.androidx.ui.graphics)
implementation(libs.androidx.ui.tooling.preview)
implementation(libs.androidx.material3)
implementation(libs.androidx.lifecycle.viewmodel.compose)
testImplementation(libs.junit)
androidTestImplementation(libs.androidx.junit)
androidTestImplementation(libs.androidx.espresso.core)
androidTestImplementation(platform(libs.androidx.compose.bom))
androidTestImplementation(libs.androidx.ui.test.junit4)
debugImplementation(libs.androidx.ui.tooling)
debugImplementation(libs.androidx.ui.test.manifest)
}
As well as my build.gradle (Project: {app-name}) file:
plugins {
alias(libs.plugins.androidApplication) apply false
alias(libs.plugins.jetbrainsKotlinAndroid) apply false
}
>Solution :
Your project’s root build.gradle plugins section needs to have this:
plugins { ... id 'com.google.dagger.hilt.android' version '2.44' apply false }
Then your app’s build.gradle file needs to have this:
plugins { id 'kotlin-kapt' id 'com.google.dagger.hilt.android' }
Finally, in your dependencies block you need to add this:
dependencies { implementation "com.google.dagger:hilt-android:2.44" kapt "com.google.dagger:hilt-compiler:2.44" }
Read more here: https://developer.android.com/training/dependency-injection/hilt-android