Just
companion object {
val instance = UtilProject()
}
will do the job because the companion object itself is a language-level singleton.
(The instance
will be created when the companion object is first called.)
--更新--
If you need to control when the singleton object is initialized, you can create one object for each class.
class UtilProject {
....
companion object {
val instance = UtilProject()
}
}
class AnotherClass {
...
companion object {
val instance = AnotherClass()
const val abc = "ABC"
}
}
fun main(args: Array<String>) {
val a = UtilProject.instance // UtilProject.instance will be initialized here.
val b = AnotherClass.abc // AnotherClass.instance will be initialized here because AnotherClass's companion object is instantiated.
val c = AnotherClass.instance
}
在这里,AnotherClass.instance
是在实际调用AnotherClass.instance
之前初始化的.当AnotherClass
的伴生对象被调用时,它被初始化.
class UtilProject {
....
companion object {
fun f() = ...
}
}
class AnotherClass {
...
companion object {
const val abc = "ABC"
}
}
object UtilProjectSingleton {
val instance = UtilProject()
}
object AnotherClassSingleton {
val instance = AnotherClass()
}
fun main(args: Array<String>) {
UtilProject.f()
println(AnotherClass.abc)
val a = UtilProjectSingleton.instance // UtilProjectSingleton.instance will be initialized here.
val b = AnotherClassSingleton.instance // AnotherClassSingleton.instance will be initialized here.
val c = UtilProjectSingleton.instance // c is a.
}
如果您不关心每个单例是何时初始化的,您也可以这样使用它:
class UtilProject {
....
companion object {
fun f() = ...
}
}
class AnotherClass {
...
companion object {
const val abc = "ABC"
}
}
object Singletons {
val utilProject = UtilProject()
val anotherClass = AnotherClass()
}
fun main(args: Array<String>) {
val a = Singletons.utilProject
val b = Singletons.anotherClass
}
In summary,
an object
or a companion object
is one singleton object in Kotlin.
You can assign variables in an object or objects, and then use the variables just like they were singletons.
object
或companion object
在首次使用时被实例化.