Kotlin Singleton Application Class

前端 未结 4 883
梦毁少年i
梦毁少年i 2021-01-31 07:56

So in android i want to make my application class a singleton.

Making it like this:

object MyApplication: Application(){}

won\'t work.

4条回答
  •  你的背包
    2021-01-31 08:35

    You can do the same thing you would do in Java, i.e. put the Application instance in a static field. Kotlin doesn't have static fields, but properties in objects are statically accessible.

    class MyApp: Application() {
    
        override fun onCreate() {
            super.onCreate()
            instance = this
        }
    
        companion object {
            lateinit var instance: MyApp
                private set
        }
    }
    

    You can then access the property via MyApp.instance.

提交回复
热议问题