avatarRanjeet Kumar yadav

Summary

Companion objects in Kotlin provide a means to associate a singleton object with a class, enabling static-like behavior, encapsulation of factory methods, and shared functionality without the need for class instantiation.

Abstract

In Kotlin, companion objects offer a unique and flexible mechanism to define class-level functionality that can be accessed without creating instances of the class. Similar to static members in Java, companion objects allow for defining constants, utility functions, and factory methods within the scope of a class, interface, or abstract class. They are singleton by nature, ensuring a single instance throughout the application's lifecycle. Companion objects can also interact with the private properties of their associated class, making them a powerful tool for encapsulating behaviors related to the class's functionality. This feature promotes better organization and maintainability of Kotlin code, as it clearly separates instance-specific and class-level concerns.

Opinions

  • The author suggests that companion objects are more powerful and provide additional functionality compared to static members in Java.
  • Companion objects are seen as beneficial for writing more organized and maintainable code by providing a clear separation between instance-specific and class-level operations.
  • The use of companion objects as factories for creating instances of a class is encouraged, as it allows for specific property configurations and can provide different variations of class instances.
  • Companion objects are not only applicable to classes but also interfaces and abstract classes, enhancing their utility across various design patterns in Kotlin.
  • The article implies that understanding and utilizing companion objects is key to leveraging the full potential of Kotlin's object-oriented programming capabilities.

Know more about Companion objects in Kotlin

Photo by Florian Klauer on Unsplash

Companion objects in Kotlin are a powerful feature that allows you to associate a singleton object with a class. They are similar to static members in Java, but with some key differences and additional functionality. In this article, we will take a closer look at companion objects and how to use them in your code.

First, let’s define what a companion object is. A companion object is a special type of object that is associated with a class. It is a singleton object, meaning that only one instance of it exists throughout the lifetime of the application. The companion object shares the same name as the class and can be accessed using the class name, without needing to create an instance of the class.

Here is an example of a class with a companion object:

class MyClass {
    companion object {
        private const val CONSTANT = "constant"
        fun someFunction() {
            // do something
        }
    }
}

In this example, the companion object is defined inside the class using the keyword companion. Inside the companion object, we have defined a constant CONSTANT and a function someFunction(). These members can be accessed using the class name, like this:

val myConstant = MyClass.CONSTANT
MyClass.someFunction()

Companion objects can also have its own property and can also access the private property of the class. For example:

class MyClass {
    private val myProperty = "property"
    companion object {
        private const val CONSTANT = "constant"
        val anotherProperty = "another property"
        fun someFunction() {
            println(myProperty)
        }
    }
}

In this example, the companion object has access to the private property myProperty and can access it inside the someFunction()

Companion objects can also be used with interfaces and abstract classes. For example:

interface MyInterface {
    companion object {
        const val INTERFACE_CONSTANT = "interface constant"
        fun interfaceFunction() {
// do something
        }
    }
}

In this example, the companion object is defined within an interface and can be accessed the same way as before, using the interface name:

val interfaceConstant = MyInterface.INTERFACE_CONSTANT
MyInterface.interfaceFunction()

One of the most powerful features of companion objects is the ability to use them as factory methods. This means that you can use a companion object to create instances of a class, rather than using the constructor directly. This can be useful for creating instances with specific properties or for creating different variations of the same class.

For example, let’s say we have a class called `Person` with a companion object that has a factory method to create instances of the class:

class Person(val name: String, val age: Int) {
    companion object {
        fun create(name: String) = Person(name, 0)
        fun create(name: String, age: Int) = Person(name, age)
    }
}

Here, we have defined two factory methods in the companion object: create(name: String) and create(name: String, age: Int). These methods can be used to create instances of the `Person` class, like this:

val person1 = Person.create("John")
val person2 = Person.create("Jane", 25)

In conclusion, companion objects are a powerful feature in Kotlin that allows you to associate a singleton object with a class. They can be used to store constants, utility methods, and factory methods that are related to the class but do not need to be associated with an instance of the class. They can also be used with interfaces and abstract classes. Understanding how to use companion objects can help you write more organised and maintainable code.

Thanks for reading.Happy learning 😄

Do support our publication by following it

Also refer to the following articles.

Kotlin
Companion Object
Android App Development
Recommended from ReadMedium