2

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.

htafoya
  • 18,261
  • 11
  • 80
  • 104
  • That would depend on what kind of initialization we're talking about, so you really should provide a more concrete example. – Michael Jun 01 '21 at 16:56
  • It's the Application class, the object is a generic Object that will be added as a property of the class during initialization. – htafoya Jun 01 '21 at 17:02
  • 1
    I meant that you should show a concrete example where we can se exactly what you're going to put inside `init`, because that affects the answer. For example, trying to call any methods that `Application` inherits from `Context` probably isn't going to work before `onCreate`. – Michael Jun 01 '21 at 17:06

1 Answers1

3

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.

Tenfour04
  • 83,111
  • 11
  • 94
  • 154