Access application context in companion object in kotlin

How can we access application context inside companion object in Android kotlin?

You can not. Your options are:

A) Provide the context as an argument to all functions that need it.

B) Instead of a Singleton companion object, create an instance of the class and provide the context as a constructor argument. Consider closing / cleaning up the instance, when not used anymore.

C) When your Application is initialized, store the application context in a globally accessible variable / property. This is arguably the most dirty solution.

1 Like