Companion object in Kotlin

Unlike Java or C#, Kotlin doesn’t have static members or member functions. Kotlin recommends to simply use package-level functions instead.
If you need to write a function that can be called without having a class instance but needs access to the internals of a class, you can write it as a member of a companion object declaration inside that class. By declaring a companion object inside our class, you’ll be able to call its members with the same syntax as calling static methods in Java/C#, using only the class name as a qualifier.

This post was originally posted at https://agrawalsuneet.github.io/blogs/companion-object-in-kotlin/ and reposted on Medium on 16th Dec 2019.

How should I declare a companion object inside a class?

Add companion keyword in front of object declaration.

class EventManager {

companion object FirebaseManager {

}
}
val firebaseManager = EventManager.FirebaseManager

Optionally, you can even remove the companion object name also. In that case the name Companion will be used.

class EventManager {

companion object {

}
}
val firebaseManager = EventManager.Companion

Let’s take an example of Singleton class where a single instance of the class exists and we get that instance using getInstance static method.

//Java codepublic class EventManager {

private static EventManager instance;

private EventManager() {

}

public static EventManager getManagerInstance() {
if (instance == null) {
instance = new EventManager();
}

return instance;
}

public boolean sendEvent(String eventName) {
Log.d("Event Sent", eventName);
return true;
}
}

Now when we try to implement the same class in the Kotlin, the private static instance and the managerInstance property will be moved to companion object. Rest of the code remains the same.

//Kotlin codeclass EventManager {

private constructor() {
}

companion object {
private lateinit var instance: EventManager

val managerInstance: EventManager
get() {
if (instance == null) {
instance = EventManager()
}

return instance
}
}

fun sendEvent(eventName: String): Boolean {
Log.d("Event Sent", eventName)
return true;
}
}

And how I use the sendEvent method?

Please continue reading at https://agrawalsuneet.github.io/blogs/companion-object-in-kotlin/

And we are done. You can read my other interesting posts here or you can enjoy my games or apps listed here. Feel free to use my open-source Android components in your app listed here. Or drop an email, if you didn’t find what you are looking for and need some help.

Reference : Kotlin Docs