Search code examples
androidandroid-studiokotlinsingletoncompanion-object

Android - Kotlin : Instantiate an object once inside the class that extends application and use it in all activities


My goal would be to instantiate an object inside the class that extends the Application class and then use it statically in all activities, es:

Suppose we have a class to be used statically or with the singleton pattern

class MyObject( arg1: Any){

   fun OneFunction(){
     .....
   }

}

Suppose we have declared the application with the name of App in the Manifest (so as to create the App class that extends Application ())


class App : Application(){

 override fun onCreate() {
        super.onCreate()

  }

}

The goal is then to be able to use the object statically in any activity


class MainActivity : AòppCompactActivity(){
     override fun onCreate(savedInstanceState: Bundle?) {
         MyObject.OneFunction()
     }
}


Solution

  • In your simple case, you're actually missing a class that would act as the globally accessible object instance container.

    class MyObject(arg1: Any){
       fun oneFunction() {
           // ...
       }
    }    
    
    class App : Application() {
       override fun onCreate() {
          super.onCreate()
          Deps.myObject = MyObject(Any())
       }
    }
    

    Where Deps is

    object Deps {
        lateinit var myObject: MyObject
    }
    

    And then

    class MainActivity : AppCompactActivity() {
         override fun onCreate(savedInstanceState: Bundle?) {
             super.onCreate(savedInstanceState)
             Deps.myObject.oneFunction()
         }
    }