Static initialisation block in Kotlin

别来无恙 提交于 2019-12-20 10:28:52

问题


What is the equivalent of a static initialisation block in Kotlin?

I understand that Kotlin is designed to not have static things. I am looking for something with equivalent semantics - code is run once when the class is first loaded.

My specific use case is that I want to enable the DayNight feature from Android AppCompat library and the instructions say to put some code in static initialisation block of Application class.


回答1:


From some point of view, companion objects in Kotlin are equivalent to static parts of Java classes. Particularly, they are initialized before class' first usage, and this lets you use their init blocks as a replacement for Java static initializers:

class C {
    companion object {
        init {
            //here goes static initializer code
        }
    }
}



回答2:


companion object  { 
    // Example for a static variable
    internal var REQUEST_CODE: Int? = 500

    // Example for a static method
    fun callToCheck(value: String): String {
        // your code
    }
}

An object declaration inside a class can be marked with the companion keyword.And under this we can use like java static method and variable.LIke classname.methodname or classname.variablename



来源:https://stackoverflow.com/questions/37262468/static-initialisation-block-in-kotlin

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!