[go: up one dir, main page]

0% found this document useful (0 votes)
5 views4 pages

Singleton Vs Companion Object

The document explains the differences between Singleton and Companion Objects in Kotlin. A Singleton Object is a globally accessible instance created using the 'object' keyword, while a Companion Object is defined within a class and allows for static-like methods and properties. It also provides a real-world example of using both in an Android application, highlighting their respective use cases.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views4 pages

Singleton Vs Companion Object

The document explains the differences between Singleton and Companion Objects in Kotlin. A Singleton Object is a globally accessible instance created using the 'object' keyword, while a Companion Object is defined within a class and allows for static-like methods and properties. It also provides a real-world example of using both in an Android application, highlighting their respective use cases.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 4

7/24/25, 9:57 AM Singleton vs Companion Object

Different between singleton object and companion object

Let's break it down simply:

1. Singleton Object
Definition: A singleton in Kotlin is declared using the object keyword. It ensures
that only one instance of the object exists in the JVM.

Usage: Used when you need a globally accessible single instance (like Utility classes,
Managers, etc.).

How it's defined:

object Singleton { fun printMessage() { println("I am a Singleton") } }


Singleton.printMessage() // Direct access

Key Points:

Created lazily on first access.

Globally accessible.

Cannot take constructor parameters.

Equivalent to static instances in Java.

2. Companion Object
Definition: A companion object is an object declared inside a class. It allows you to
define static-like methods and properties inside a class.

Usage: Used to write functions or properties related to a class but not tied to an
instance.

How it's defined:

class MyClass { companion object { fun printMessage() { println("I am a


Companion Object") } } } MyClass.printMessage() // Access via Class Name

Key Points:

Can access private members of the enclosing class.

Only one companion object per class.

Can implement interfaces.

Equivalent to static methods/properties in Java.

Major Differences
https://chatgpt.com/c/6881964e-c5f0-800f-a8dd-826ab7523106 1/4
7/24/25, 9:57 AM Singleton vs Companion Object

Singleton Object Companion Object

Declared at top-level using object . Declared inside a class using companion object .

Globally accessible singleton instance. Acts like a static member of a class.

No enclosing class needed. Tied to the enclosing class.

Cannot access private members of any class. Can access private members of the enclosing
class.

Example: Singleton.printMessage() Example: MyClass.printMessage()

Simple Analogy
Singleton Object Companion Object

Like a global utility object. Like a static object inside a class.

Do you want me to show a real-world practical example where both are used together in
an Android project (like Repository Singleton + DAO Companion Object)?

Explain more and real world practical example

Perfect! Let’s go deeper and see a real-world Android example where both Singleton
Object and Companion Object are used together in a practical way.

Scenario:
You're building an Android App that interacts with a Room Database. You need:

1. A singleton Repository that is used across the app.

2. A companion object in the DAO (or Utility class) for static-like access.

Example Breakdown:

1. Singleton Object — Repository Pattern


You want a single instance of Repository to manage data operations.

https://chatgpt.com/c/6881964e-c5f0-800f-a8dd-826ab7523106 2/4
7/24/25, 9:57 AM Singleton vs Companion Object

object UserRepository { private val userList = mutableListOf<String>() fun


addUser(name: String) { userList.add(name) } fun getAllUsers(): List<String> =
userList }

➡ Why Singleton?
You don’t want multiple instances of UserRepository .

Global access throughout the app.

Holds in-memory data/state.

2. Companion Object — Static Factory Method


In your DAO or Helper Class, you want to provide a static method to create dummy data.

class UserUtils { companion object { fun getDummyUsers(): List<String> {


return listOf("Alice", "Bob", "Charlie") } } }

➡ Why Companion Object?


Tied to UserUtils class.

You can call UserUtils.getDummyUsers() without creating an instance.

Acts like a static method in Java.

3. Using Both Together


Here’s how you'd use both in your Activity or ViewModel:

fun main() { // Access Companion Object method val dummyUsers =


UserUtils.getDummyUsers() // Add dummy users to Singleton Repository
dummyUsers.forEach { UserRepository.addUser(it) } // Access Singleton
Repository data val allUsers = UserRepository.getAllUsers() println("All
Users: $allUsers") }

Output:

All Users: [Alice, Bob, Charlie]

Real-world Android Example (Room DB Style)

DAO with Companion Object:

@Dao interface UserDao { @Query("SELECT * FROM user") fun getAllUsers():


List<User> companion object { const val TABLE_NAME = "user" } }

https://chatgpt.com/c/6881964e-c5f0-800f-a8dd-826ab7523106 3/4
7/24/25, 9:57 AM Singleton vs Companion Object

Repository as Singleton:

object UserRepository { lateinit var userDao: UserDao fun initialize(dao:


UserDao) { userDao = dao } fun fetchAllUsers(): List<User> { return
userDao.getAllUsers() } }

Usage in ViewModel or Activity:

UserRepository.initialize(database.userDao()) val users =


UserRepository.fetchAllUsers()

Key Takeaways
Singleton Object Companion Object

Application-level single instance (Repository, Class-level static properties/methods (Utils,


Manager, etc.). Constants).

Best for holding shared data or service Best for factory methods, constants, or static
instances. functions inside classes.

Created lazily on first access. Always exists with the class.

When to Use What?


Use Singleton Object When: Use Companion Object When:

You need a global object instance (e.g., You need static-like methods or constants inside a
Repository, Logger). class (e.g., Factory methods, Constants).

https://chatgpt.com/c/6881964e-c5f0-800f-a8dd-826ab7523106 4/4

You might also like