Noé Mastrorillo
Noé Mastrorillo

Reputation: 309

Android Kotlin retrieve context from an object

Hey I'm using Android Studio with Kotlin and I have an activity and a service that both needs to call same methods, so I created an object with theses methods in it, which would be like a utils class.

The problem is that the methods depend on a field that needs the application context to be created, and the only way I found to retrieve the context was to pass it through the constructor, but as it's an object I can't do that.

How could I keep that object behaviour and retrieve the application context ?

Upvotes: 0

Views: 665

Answers (1)

AndroidEngineX
AndroidEngineX

Reputation: 1501

In Kotlin, an object behaves like a static util class(not exactly at bytecode level) so there are only a few options that you could do

  1. Pass the the context in every util method in the object which needs the context
  2. Make an Application class and keep a global reference of the application context and use it everywhere by making it lateinit var and initialising it in Application`s onCreate method
  3. Or use DI for injection of Application context and instead of using Object use Singleton scoped utility that is injected everywhere

Upvotes: 1

Related Questions