Search code examples
androidkotlinandroid-manifest

How to use kotlin to define an Android Application class?


My code:

 object MyApplication : Application() {

      override fun onCreate() {
          super.onCreate()
          initOkHttp()
      }
   }

when I declare MyApplication in AndroidManifest, it says has no default constructor.

Can anybody help?

enter image description here


Solution

  • The solution ais to use the class keyword instead of object. An object declaration in Kotlin is a singleton, which means it only has a single instance, and it has a private constructor to prevent the creation of any other instances.

    In the case of an Application class on Android however, the framework itself will create the instance when your application launches, and this requires an accessible private constructor.