Access application context in companion object in kotlin


#1

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


#2

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.