0

The Dagger Component

@Component
public interface ApplicationComponent {
    void inject(LoginActivity loginActivity);
}

Application class

class MyApplication: Application() {
    val appComponent = DaggerApplicationComponent.create()
}

Activity

class LoginActivity: Activity() {
    @Inject lateinit var loginViewModel: LoginViewModel
}

override fun onCreate(savedInstanceState: Bundle?) {
        (applicationContext as MyApplication).appComponent.inject(this)
        super.onCreate(savedInstanceState)
    }

In my activity's onCreate() , I'm casting my applicationContext to Application class and then accessing the variable inside it. Can someone please elaborate on how does it work and why the casting is needed.

newbie_coder
  • 225
  • 2
  • 9
  • because you `appComponent` val is in your `MyApplication` class but no system/kotlin classes, `applicationContext` maybe a `Context` or `Application` instance which doesn't have `appComponent` val, so you will need to cast it before. – Ayaka_Ago Aug 10 '22 at 05:28

1 Answers1

0

Context is an abstract class with multiple implementations. Your component is in the MyApplication class and you have the following hierarchy:

Context

|

ContextWrapper

|

Application

|

MyApplication

As you can see here you get a Context:

    @Override
    public Context getApplicationContext() {
        return mBase.getApplicationContext();
    }

So you need to cast to have the implementation that you need with the corresponding accessible variable in your case: the component.

You should check the Context hierarchy:

https://developer.android.com/reference/android/content/Context

Also please check this article:

https://medium.com/@ali.muzaffar/which-context-should-i-use-in-android-e3133d00772c

What is 'Context' on Android?

Yavor Mitev
  • 1,363
  • 1
  • 10
  • 22