Welcome back to CodeYourCraft! Today, we're diving into the fascinating world of Kotlin's Object Declaration, also known as the Singleton pattern. This pattern ensures that a class has only one instance and provides a global point of access to it. Let's get started! 📝
A Singleton is a design pattern that restricts the instantiation of a class to a single instance. It is useful when you need to have only one object that can be accessed globally.
In Kotlin, the simplest way to create a Singleton is by declaring a class with an object keyword.
Here's a simple example of a Singleton class in Kotlin:
object MySingleton {
fun sayHello() = "Hello, World!"
}In the above code, MySingleton is a Singleton class with a single function sayHello(). You can access this function anywhere in your code by just calling MySingleton.sayHello().
If you need to initialize a Singleton with a constructor, you can create a private constructor and provide a companion object to create the instance:
class MySingleton private constructor() {
companion object {
val instance = MySingleton()
fun sayHello() = "Hello, World!"
}
}Now, you can access the sayHello() function using MySingleton.sayHello(), and the instance will be created when the first call is made.
What does the `object` keyword in Kotlin do?
With this, we've covered the basics of creating Singletons in Kotlin. Singletons are a powerful tool to ensure that only one instance of a class is created, and they are useful in many real-world scenarios such as managing resources, logging, and cache.
Happy coding! 🚀