Internals of object class - Singleton in Kotlin
From Kotlin ‘object’ to JVM bytecode: The internals of singleton creation
Kotlin’s “object” keyword looks simple, but behind the scenes, it’s smartly designed to ensure thread safety and lazy initialization.
Let me explain how Kotlin implements the object singleton pattern internally.
For example, we created an object class as below:
object OutcomeSchool {
fun learnInternals() = “Hello dev, start learning the internals”
}Internally, the compiler generates a final class with a private constructor:
public final class OutcomeSchool {
private OutcomeSchool() { }
}It creates a static INSTANCE field and initializes it in a static block:
public final class OutcomeSchool {
public static final OutcomeSchool INSTANCE;
static {
OutcomeSchool instance = new OutcomeSchool();
INSTANCE = instance;
}
}Note:
Lazy initialization: The singleton instance is created only when it is accessed for the first time.
Thread safety: It is guaranteed by the JVM class loading mechanism. The static initialization is automatically thread-safe without additional synchronization.
Prepare for your Android Interview: Android Interview Questions and Answers
Thanks
Amit Shekhar
Founder, Outcome School


