简体   繁体   English

Android - 在 kotlin 中重载 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 中实现这样的东西:

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;我一直使用OnCreate方法来执行我的应用程序的所有初始化,并且我非常确信重载构造函数是错误的,即使它们是可选参数; but I have a slight doubt that it may work.但我有点怀疑它是否可行。

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.应用程序 class 仅由操作系统实例化,并通过调用空构造函数通过反射完成。 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.将此SomeClass()实例化放在初始化块中会更有意义。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM