androidkotlinandroid-lifecycleandroid-application-class

Android - Is it correct to overload the Application class constructor in kotlin?


Someone proposed to implement something as this in the main Application class:

class MyApplication(someProp = SomeClass()): Application {
    init {
        ... do some initializations
    }
}

I have always used the OnCreate method to perform all initializations of my application and I'm pretty confident that it is wrong to overload the constructor even if they are optional parameters; but I have a slight doubt that it may work.


Solution

  • This will work since you provide the default value for that constructor parameter, so an empty constructor is also generated, and that's the one that will be used.

    However, I don't see any purpose in doing this. The Application class is only instantiated by the OS, and it is done via reflection, by calling the empty constructor. So by adding this parameter, it is communicating that there is some other intended use for it, but it's an impossible case. That is obtuse code. It would make more sense to put this SomeClass() instantiation inside an initialization block.