Kotlin静态方法和变量 [英] Kotlin static methods and variables
问题描述
我希望能够将类实例保存到公共静态变量,但是我不知道如何在Kotlin中做到这一点.
I want to be able to save a class instance to a public static variable but I can't figure out how to do this in Kotlin.
class Foo {
public static Foo instance;
public Foo() {
instance = this;
}
}
推荐答案
与Java静态字段最接近的东西是伴随对象.您可以在此处找到有关它们的文档参考: https://kotlinlang.org /docs/reference/object-declarations.html#companion-objects
The closest thing to Java's static fields is a companion object. You can find the documentation reference for them here: https://kotlinlang.org/docs/reference/object-declarations.html#companion-objects
您在Kotlin中的代码如下所示:
Your code in Kotlin would look something like this:
class Foo {
companion object {
lateinit var instance: Foo
}
init {
instance = this
}
}
如果要将字段/方法以静态形式公开给Java调用者,则可以应用
If you want your fields/methods to be exposed as static to Java callers, you can apply the @JvmStatic
annotation:
class Foo {
companion object {
@JvmStatic lateinit var instance: Foo
}
init {
instance = this
}
}
这篇关于Kotlin静态方法和变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!