Skip to content

How to create a Singleton class in Kotlin? #4

Discussion options

You must be logged in to vote

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
}

Replies: 1 comment

Comment options

You must be logged in to vote
0 replies
Answer selected by mohamedebrahim96
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
bug Something isn't working
2 participants