8

I'm learning dependency injection by the article with the project

The Code A need instance an object navigator by dependency injection , so the author use Code B to implement it, you can see it here.

I'm very strange that the class AppNavigatorImpl has implemented the class AppNavigator by dependency injection in Code C, so I think Code D will work well.

Can I use @Inject lateinit var navigator: AppNavigatorImpl instead of @Binds abstract fun bindNavigator(impl: AppNavigatorImpl): AppNavigator ?

Code A

@AndroidEntryPoint
class MainActivity : AppCompatActivity() {

    @Inject lateinit var navigator: AppNavigator
   

    ...
}

Code B

@InstallIn(ActivityComponent::class)
@Module
abstract class NavigationModule {

    @Binds
    abstract fun bindNavigator(impl: AppNavigatorImpl): AppNavigator
}

Code C

class AppNavigatorImpl  @Inject constructor(private val activity: FragmentActivity) : AppNavigator {

    override fun navigateTo(screen: Screens) {
        val fragment = when (screen) {
            Screens.BUTTONS -> ButtonsFragment()
            Screens.LOGS -> LogsFragment()
        }

        activity.supportFragmentManager.beginTransaction()
            .replace(R.id.main_container, fragment)
            .addToBackStack(fragment::class.java.canonicalName)
            .commit()
    }
}

Code D

@AndroidEntryPoint
class MainActivity : AppCompatActivity() {

    @Inject lateinit var navigator: AppNavigatorImpl
   

    ...
}
HelloCW
  • 843
  • 22
  • 125
  • 310

1 Answers1

0

Technically, you can.

The question is, whether you actually want to do that. Usually you want to depend on abstractions, not concretions (dependency inversion principle).

If you'd injected the AppNavigatorImpl, then you depend on concretion instead of it's abstraction AppNavigator.

Also, that page in the codelab teaches how to inject an interface (or an abstract class) as those can't have constructor annotated with @Inject.

In your codebase, you usually need to decide whether it's necessary to have this abstraction or not.

mlykotom
  • 4,850
  • 1
  • 22
  • 27