Companion object cho phép định nghĩa các thành viên kiểu static (hằng số, factory method) bên trong class, thuộc về class chứ không phải instance.
- Mỗi class chỉ có một companion object.
- Có thể gọi trực tiếp mà không cần tạo instance:
MyClass.myStaticMethod(). - Giống
statictrong Java nhưng linh hoạt hơn vì có thể implement interface.
A companion object allows you to define static-like members (constants, factory methods) within a class that belong to the class itself, not instances.
- Only one companion object is allowed per class.
- You can call companion object members without creating an instance:
MyClass.myStaticMethod(). - It's similar to
staticin Java but offers better encapsulation and allows implementing interfaces.