代码之家  ›  专栏  ›  技术社区  ›  Devrath

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

  •  -1
  • Devrath  · 技术社区  · 6 年前

    如何在Kotlin中编写等效代码,我需要使用定义的静态变量

    public class ThisForThatApplication extends Application {
    
        static ThisForThatApplication appInstance;
    
        public static ThisForThatApplication getAppInstance() {
            if (appInstance == null) {
                appInstance = new ThisForThatApplication();
            }
            return appInstance;
        }
    }
    
    3 回复  |  直到 6 年前
        1
  •  0
  •   Goku Farhana Naaz Ansari    6 年前

    试试这个方法

    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

        2
  •  0
  •   Sharan    6 年前

    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()
    }
    }
    
        3
  •  0
  •   yyunikov    6 年前

    没有 static 科特林的概念。但是,您可以实现相同的用途 companion objects . 查看Kotlin object expression and declaration 更多解释。

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

    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 在伴生对象的底部,只允许thisforthattapplication类设置该值。