Complete the code to annotate an Android Application class for Hilt.
import android.app.Application import dagger.hilt.android.HiltAndroidApp @[1] class MyApp : Application() {}
The @HiltAndroidApp annotation tells Hilt to generate components for the Application class.
Complete the code to inject a dependency into an Android Activity using Hilt.
import android.os.Bundle import androidx.activity.ComponentActivity import dagger.hilt.android.AndroidEntryPoint import javax.inject.Inject @AndroidEntryPoint class MainActivity : ComponentActivity() { @Inject lateinit var repository: [1] override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) } }
The dependency type to inject must be specified. Here, MyRepository is the class to be injected.
Fix the error in the Hilt module by completing the annotation to provide a singleton instance.
import dagger.Module import dagger.Provides import dagger.hilt.InstallIn import dagger.hilt.components.SingletonComponent import javax.inject.Singleton @Module @InstallIn(SingletonComponent::class) object AppModule { @[1] fun provideService(): ApiService { return ApiServiceImpl() } }
The @Singleton annotation ensures the provided instance is a singleton in the app scope.
Fill both blanks to create a Hilt module that provides a Retrofit instance.
import dagger.Module import dagger.Provides import dagger.hilt.InstallIn import dagger.hilt.components.SingletonComponent import retrofit2.Retrofit import retrofit2.converter.gson.GsonConverterFactory import javax.inject.Singleton @Module @InstallIn(SingletonComponent::class) object NetworkModule { @Singleton @Provides fun provideRetrofit(): Retrofit { return Retrofit.Builder() .baseUrl([1]) .addConverterFactory([2]) .build() } }
The base URL must be a string with the API endpoint. The converter factory is created by calling GsonConverterFactory.create().
Fill all three blanks to create a Hilt ViewModel with an injected repository and a saved state handle.
import androidx.lifecycle.SavedStateHandle import androidx.lifecycle.ViewModel import dagger.hilt.android.lifecycle.HiltViewModel import javax.inject.Inject @HiltViewModel class UserViewModel @Inject constructor( private val repository: [1], private val savedStateHandle: [2] ) : ViewModel() { fun getUserId(): String? { return savedStateHandle.get<String>([3]) } }
The repository type is UserRepository. The saved state handle type is SavedStateHandle. The key to get the user ID is the string "userId".