如何在kotlin中编写等价代码,我需要使用静态变量定义的
public class ThisForThatApplication extends Application {
static ThisForThatApplication appInstance;
public static ThisForThatApplication getAppInstance() {
if (appInstance == null) {
appInstance = new ThisForThatApplication();
}
return appInstance;
}
}
尝试这种方式
class ThisForThatApplication : Application() {
companion object {
@JvmField
var appInstance: ThisForThatApplication? = null
@JvmStatic fun getAppInstance(): ThisForThatApplication {
return appInstance as ThisForThatApplication
}
}
override fun onCreate() {
super.onCreate()
appInstance=this;
}
}
有关详细信息,请阅读Static Fields
&Static Methods
Kotlin中没有static
概念。但是,使用配套对象也可以实现同样的效果。查看Kotlin对象表达式和声明以获得更多解释。
由于在您的示例中,您只想创建一个Singleton,因此可以执行以下操作:
class ThisForThatApplication: Application() {
companion object {
val instance = ThisForThatApplication()
}
}
然而,当您正在创建Android应用程序类时,就Android而言,最好在onCreate((方法中初始化实例:
class ThisForThatApplication : Application() {
companion object {
lateinit var instance: ThisForThatApplication
private set
}
override fun onCreate() {
super.onCreate()
ThisForThatApplication.instance = this
}
}
伴随对象底部的private set
将只允许ThisForThatApplication类设置该值。
Kotlin中的应用程序类和静态变量
class App : Application() {
init {
instance = this
}
companion object {
private var instance: App? = null
fun applicationContext(): Context {
return instance!!.applicationContext
}
}
override fun onCreate() {
super.onCreate()
}
}