How to create singleton in Kotlin?

Technology CommunityCategory: KotlinHow to create singleton in Kotlin?
VietMX Staff asked 3 years ago

Just use object.

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();
   }
}

This is the preferred way to implement singletons on a JVM because it enables thread-safe lazy initialization without having to rely on a locking algorithm like the complex double-checked locking.