Kotlin 的静态初始化模块

在 Kotlin,相当于 静态初始化块静态初始化块的是什么?

我知道科特林的设计不是为了静态的东西。我正在寻找具有等效语义的东西-代码运行一次,当类第一次加载。

我的具体用例是,我想启用来自 Android AppCompat 库的 DayNight 特性,并且 说明书表示将一些代码放入 Application类的静态初始化块中。

21979 次浏览

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
}
}
}

@voddan it's not an overkill, actually this is what suggested on the site of Kotlin: "A companion object is initialized when the corresponding class is loaded (resolved), matching the semantics of a Java static initializer." Semantic difference between object expressions and declarations

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