如何在kotlin中编写等效代码,我需要使用定义的静态变量
public class ThisForThatApplication extends Application {
static ThisForThatApplication appInstance;
public static ThisForThatApplication getAppInstance() {
if (appInstance == null) {
appInstance = new ThisForThatApplication();
}
return appInstance;
}
}
答案 0 :(得分:0)
尝试这种方式
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
答案 1 :(得分:0)
在Kotlin中没有static
概念。但是,您可以使用companion objects实现相同的目的。请查看Kotlin object expression and declaration了解更多说明。
由于在您的示例中您只想创建一个Singleton,因此可以执行以下操作:
class ThisForThatApplication: Application() {
companion object {
val instance = ThisForThatApplication()
}
}
但是,当您创建Android Application类时,就Android而言,以onCreate()方法初始化实例会更好:
class ThisForThatApplication : Application() {
companion object {
lateinit var instance: ThisForThatApplication
private set
}
override fun onCreate() {
super.onCreate()
ThisForThatApplication.instance = this
}
}
伴随对象底部的 private set
仅允许ThisForThatApplication类设置该值。
答案 2 :(得分:0)
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()
}
}