Internals of object class - Singleton in Kotlin 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. Follow Outcome School to learn internals. Keep Learning, Keep Sharing, and Keep Growing. Software engineers like you join Outcome School to achieve the outcome that is a high-paying tech job. Join Outcome School: https://outcomeschool.com #OutcomeSchool #SoftwareEngineer #Tech #AndroidDev #Android #Kotlin
Impressive
Hey AMIT SHEKHAR, Great content. But I think the byte code needs to be updated as a final variable cannot be assign a value at later point in time. It should look something like - public final class OutcomeSchool { public static final OutcomeSchool INSTANCE = new OutcomeSchool(); private OutcomeSchool() { } }
Valuable info
This is great
Great
Great
Follow Outcome School for knowledge-packed content.