Kotlin Companion Object: In this tutorial, you will learn to create and use companion objects in your Kotlin program with the assistance of examples.
In Kotlin or some other programming language like Java and C#, at whatever point we need to call the technique or at whatever point we need to access to the members from a class then we create the object of the class and with the assistance of that object, we access the members from the class. A typical Kotlin illustration of the equivalent is:
class ToBeCalled { fun callMe() = println("You are calling me :)") } fun main(args: Array<String>) { val obj = ToBeCalled() // calling callMe() method using object obj obj.callMe() }
In the above example, we are calling the callMe() technique for the ToBeCalled class by creating one object of the ToBeCalled class and afterward with the assistance of that object, the callMe() strategy is called.
Before taking about companion objects, let’s take an example to access members of a class.
class Person { fun callMe() = println("I'm called.") } fun main(args: Array<String>) { val p1 = Person() // calling callMe() method using object p1 p1.callMe() }
Here, we created an object p1 of the Person class to call callMe() technique. That is the manner by which things ordinarily work.
Be that as it may, in Kotlin, you can likewise call callMe() technique by using the class name, i.e, Person for this situation. For that, you need to create a companion object by marking the object declaration with a companion watchword.
Example: Companion objects
class Person { companion object Test { fun callMe() = println("I'm called.") } } fun main(args: Array<String>) { Person.callMe() }
At the point when you run the program, the output will be:
I'm called.
In the program, Test object assertion is marked with watchword companion to create a companion object. Thus, it is feasible to call callMe() technique by using the name of the class as:
Person.callMe()
The name of the companion object is optional and can be omitted.
class Person { // name of the companion object is omitted companion object { fun callMe() = println("I'm called.") } } fun main(args: Array<String>) { Person.callMe() }
On the off chance that you know about Java, you may relate companion objects with static techniques (even though how they work internally is totally different).
The companion objects can access private individuals from the class. Henceforth, they can be used to execute the factory method patterns..
Thanks for reading! We hope you found this tutorial helpful and we would love to hear your feedback in the Comments section below. And show us what you’ve learned by sharing your photos and creative projects with us.