Android 如何在kotlin中定义应用程序类和静态变量

Android 如何在kotlin中定义应用程序类和静态变量,android,kotlin,Android,Kotlin,如何在kotlin中编写等效代码,我需要使用定义的静态变量 public class ThisForThatApplication extends Application { static ThisForThatApplication appInstance; public static ThisForThatApplication getAppInstance() { if (appInstance == null) { appIns

如何在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;
    }

}

有关更多信息,请阅读&

Kotlin中没有
静态概念。但是,您可以通过使用来实现相同的目标。查看Kotlin了解更多解释

因为在您的示例中,您只想创建一个单例,所以可以执行以下操作:

class ThisForThatApplication: Application() {
    companion object {
        val instance = ThisForThatApplication()
    }
}
但是,在创建Android类时,就Android而言,在方法中初始化实例会更好:


伴生对象底部的
私有集
将仅允许该应用程序类设置值。

应用程序类和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()
}
}

使用Android Studio的kotlintry的伴随块
通过按
Ctrl+Alt+Shift+K
转换为Kotlin
插件作为旁注,您不需要自己在Android中实例化
应用程序。这总是由框架完成的。设置
appInstance
字段的正确位置是
onCreate
方法。
返回实例!!。applicationContext
-如果实例为空,它将抛出NullPointerException。
class App : Application() {

init {
    instance = this
}

companion object {
    private var instance: App? = null

    fun applicationContext(): Context {
        return instance!!.applicationContext
    }
}

override fun onCreate() {
    super.onCreate()
}
}