Difference between a class and object in Kotlin
In Kotlin, a class is a blueprint for creating objects — it defines attributes and behavior. On the other hand, an object is an instance of a class, which carries specific state and behavior. Here's a simple demonstration:
Moreover, Kotlin additionally uses object
keyword in a unique context of singleton design pattern, for defining a single instance composition.
Digging deeper into classes and objects
Singleton objects: "There can be only one!"
In Kotlin, object
keyword allows defining singleton objects — single instance entities, without any direct constructor to create instances ad libitum.
Companion objects: "Every class needs a buddy!"
Kotlin meets the static needs via companion objects — bundled with the respective class and serving class-level functionality.
Interoperability: Playing nice with Java
Kotlin employs the @JvmStatic
annotation to expose companion or object functions as static methods when called from Java, keeping the interoperability smooth.
Top-Level functions: "No class? No problem!"
Kotlin lets you define functions at the top-level, making them part of the package and accessible without any object.
Interplay with memory efficiency
Singletons' single-instance limit enhances memory efficiency, sparing your program from repeated object allocations.
Practical scenarios
Conversion of Java statics
The shift from Java to Kotlin transitions static variables/methods into object
or companion object
functions, conforming to Kotlin's object-friendly design.
Initialization rules
Despite bits of resemblance to static in use, object
and companion objects are not initialized at load. Kotlin keeps it lazy, initialising these when they are accessed first.
Data classes: A star cutout!
Data classes are a unique scaffold in Kotlin. These auto-generate boilerplate — toString()
, equals()
, hashCode()
— making life a wee bit easier!
Accessing members: No class needed
Whether it's a simple object or a companion object, you call their functions directly with the name, no need for an instance.
References
Was this article helpful?