Kotlin Object Declaration (Singleton) 🎯

beginner
14 min

Kotlin Object Declaration (Singleton) 🎯

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! 📝

What is a Singleton in Kotlin? 💡

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.

Declaring a Singleton in Kotlin 💡

Here's a simple example of a Singleton class in Kotlin:

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().

Creating a Singleton with Constructors 💡

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:

kotlin
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.

Quiz Time! 💡

Quick Quiz
Question 1 of 1

What does the `object` keyword in Kotlin do?

Conclusion 💡

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! 🚀