Does HILT supports injecting generic types?

Viewed 1085

I am getting below error during compilation, using HILT for DI.

Component methods cannot have type variables

Its complaining about the below code

public abstract class BaseDialogFragment extends DialogFragment {

        @EntryPoint
        @InstallIn(ApplicationComponent.class)
        interface BaseDialogFragmentEntryPoint {
                public <T extends ViewModelBase> T T();
        }

        protected ViewModelBase dataContext;

        protected <T extends ViewModelBase> T configure(Class<T> type)
        {
                BaseDialogFragmentEntryPoint baseDialogFragmentEntryPoint = EntryPointAccessors.fromApplication(getActivity().getApplicationContext(), BaseDialogFragmentEntryPoint.class);
                T viewModel = baseDialogFragmentEntryPoint.T();
                this.dataContext = viewModel;
                return viewModel;
        }

}

ViewModelBase class is extended by number of classes.

Does HILT support injecting generic objects? I have not found much information on this regarding HILT.

1 Answers

If your goal is to override an instance of ViewModel from your "BaseFragment" to "ChildFragment", you can create an abstract variable in Base, and initialize it using by viewModels() delegate that kotlin provides. In order to be able to create the instance of ViewModel, you'll also need to annotate your ViewModel with @HiltViewModel annotation. Checkout the example from documentaion

And here is example that I use

abstract class BaseFragment<T : ViewModel> : Fragment() {
     abstract val viewModel: T
     ......
}
@AndroidEntryPoint
class MyFragment: BaseFragment<MyViewModel>() {
    override val viewModel: MyViewModel by viewModels()
    .....
}
@HiltViewModel
class MyViewModel
@Inject constructor() : ViewModel() {
    ......
}
Related