I want to know way to create singleton class, so that my Util class instantiate only once per app. However when I converted my Java class to kotlin, below code was generated
Just
companion object {
val instance = UtilProject()
}
will do the job because the companion object itself is a language-level singleton.
(The instance will be assigned when the companion object is first called.)
-- Updated --
If you need to adjust when the singleton object should be initilized, 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) {
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
}
Here, AnotherClass.instance is initialized before AnotherClass.instance is actually called. It is initialized when AnotherClass's companion object is called.
To prevent being initialized before when needed, you can use like this:
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) {
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.
}
If you don't care when each singleton is initialized, you can also use like this:
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) {
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 or companion object is instantiated when it is first used.
vals and vars in an object are initialized when the object is first instantiated (i.e., when the object is first used).