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.
objectIt 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.
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_()}
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:
How to use companion objects in Kotlin
Learn how Kotlin's companion objects enable calling class members without creating an instance, similar to static methods in Java.
How to create a singleton class in Kotlin
Learn how to implement the singleton pattern in Kotlin using the object declaration for single-instance access to resources.
What are sealed classes in Kotlin?
Learn how sealed classes in Kotlin restrict inheritance to a predefined set, enhancing control and type safety in coding.
What is the purpose of Companion Object in Kotlin?
Learn how Kotlin's companion objects create static properties and functions, centralize shared attributes, and implement factory methods for cleaner, maintainable code.
Data types in Kotlin
Learn how Kotlin categorizes data types into primitive and reference types, supporting numbers, characters, booleans, arrays, strings, classes, functions, and nullable types.
Descending sort of 0s, 1s, and 2s in kotlin
Learn how to modify the Dutch National Flag algorithm in Kotlin to efficiently sort arrays of 0s, 1s, and 2s in descending order with O(N) time and O(1) space complexity.
Free Resources