java Kotlin 中的静态初始化块
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/37262468/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Static initialisation block in Kotlin
提问by Marcin Koziński
What is the equivalent of a static initialisation blockin Kotlin?
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.
我知道 Kotlin 被设计成没有静态的东西。我正在寻找具有等效语义的东西 - 代码在第一次加载类时运行一次。
My specific use case is that I want to enable the DayNight feature from Android AppCompat library and the instructionssay to put some code in static initialisation block of Application
class.
我的具体用例是我想从 Android AppCompat 库启用 DayNight 功能,并且说明中说要将一些代码放在Application
类的静态初始化块中。
回答by hotkey
From some point of view, companion object
sin 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:
从某种角度来看,Kotlin 中的companion object
s相当于 Java 类的静态部分。特别是,它们在类第一次使用之前被初始化,这让你可以使用它们的init
块来替代 Java 静态初始化器:
class C {
companion object {
init {
//here goes static initializer code
}
}
}
回答by abhilasha Yadav
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
类内的对象声明可以用伴随关键字标记。在此之下我们可以使用像java静态方法和变量。比如类名.方法名或类名.变量名