Singleton class in Kotlin

If I want to define Singleton , then it’ll be something like this:
A Singleton is a software design pattern that guarantees a class has one instance only and a global point of access to it is provided by that class.
Singleton Pattern ensures that only one instance would be created and it would act as a single point of access thereby ensuring thread safety.
In java code, it’ll look like this:
But the above codes are dangerous, especially if it’s used in different threads. If two threads access this singleton at a time, two instances of this object could be generated.
The synchronized keyword ensures that there are no thread interferences when creating the instance.
If you want to recreate this in Kotlin, then the code close to it will be:
In this case, The by lazy{}indicates it will be computed on the first access only. The evaluation of lazy properties is synchronized, the value is computed only in one thread, and all threads will see the same value.
Kotlin has a default implementation of the above requirement, which is
Yeah!!!. That’s it. Only one line of code and you can avoid all those lines of code. An object is just a data type with a thread-safe singleton implementation.

Object declarations

Just like a variable declaration, an object declaration is not an expression, and cannot be used on the right-hand side of an assignment statement. Object declaration’s initialization is thread-safe.
To refer to the object, we use its name directly.
Objects can have supertypes:

Summarize:

  • Kotlin’s representation of a Singleton class requires the object keyword only.
  • An object class can contain properties, functions and the init method.
  • The constructor method is NOT allowed.
  • An object cannot be instantiated in the way a class is instantiated.
  • An object gets instantiated when it is used for the first time providing lazy initialization.
  • Object declaration’s initialization is thread-safe.

Comments