Update:任何只需要所谓的“单例”(有时称为“服务”(Android 除外))的人(例如 OP),都应该简单地使用 Kotlin 的内置函数:
object Foo {
// Done, this already does what OP needed,
// because the boilerplate codes (like static field and constructor),
// are taken care of by Kotlin.
}
(Like Roman rightly pointed out in the comment-section.)
之前的回答;如果您有(或计划有)多个static
变量,然后继续阅读:
与 Java 静态字段最接近的是伴生对象。您可以在这里找到它们的文档参考:https://kotlinlang.org/docs/reference/object-declarations.html#companion-objects
您的 Kotlin 代码将如下所示:
class Foo {
companion object {
private lateinit var instance: Foo
fun get(): Foo {
return instance;
}
}
init {
if (instance == null) {
instance = this
}
}
}
如果您希望将字段/方法作为静态公开给 Java 调用者,您可以应用@JvmStatic注解:
class Foo {
companion object {
private lateinit var instance: Foo
@JvmStatic fun get(): Foo {
return instance;
}
}
init {
if (instance == null) {
instance = this
}
}
}
Note that @JvmStatic
不需要任何导入(因为它是 Kotlin 的内置功能)。