• +91 9723535972
  • info@interviewmaterial.com

Kotlin Interview Questions and Answers

Question - How can you create a singleton in Kotlin?

Answer -

We can create a singleton in Kotlin by using an object.

Syntax:

object SomeSingleton  
The above Kotlin object will be compiled to the following equivalent Java code:

public final class SomeSingleton {  
   public static final SomeSingleton INSTANCE;  
   private SomeSingleton() {  
      INSTANCE = (SomeSingleton)this;  
      System.out.println("init complete");  
   }  
   static {  
      new SomeSingleton();  
   }  
}  
The above way is preferred to implement singletons on a JVM because it enables thread-safe lazy initialization without relying on a locking algorithm like the complex double-checked locking.

Comment(S)

Show all Coment

Leave a Comment




NCERT Solutions

 

Share your email for latest updates

Name:
Email:

Our partners