How to create a singleton class in Kotlin

The singleton is a useful design pattern that can limit the number of class instances to one. It is extremely useful when only a single instance should access a resource to avoid issues, such as hardware interfaces and log writing.

To learn more about the singleton design pattern, visit this Answer.

Generally, singleton classes must be defined to have certain characteristics—a private constructor and a static method that returns the singleton instance—for it to exhibit singleton behavior. However, Kotlin provides a neat way to create a singleton class using its object declaration functionality.

Creating singleton classes using object

It is effortless to declare singletons in Kotlin using its object declaration: object singleton_name. It is important to note that object declaration is not an expression and cannot be used on the right-hand side of an assignment statement. Let's look at some code with Kotlin's object declaration.

Code example

object singleton_ {
var var_: String = "This is a singleton var"
fun fun_() = println("This is a singleton fun")
}
fun main() {
println(singleton_.var_)
singleton_.fun_()
}

Code explanation

  • Lines 1–4: We declare an object with the name singleton_. This is our singleton.

  • Line 2: We declare a variable of singleton_ called var_.

  • Line 3: We declare a function of singleton_ called fun_.

  • Lines 6–9: We contain the main function.

  • Line 7: We print the var_ variable from singleton_.

  • Line 8: We call the fun_ method of singleton_.

Unlock your potential: Kotlin series, all in one place!

To continue your exploration of Kotlin, check out our series of Answers below:

Free Resources

Copyright ©2025 Educative, Inc. All rights reserved