1.

What do you understand about Companion Object in the context of Kotlin?

Answer»

In some languages, such as Java, the STATIC keyword is used to declare class members and utilise them without creating an object, i.e. by simply calling them by their class name. In Kotlin, there is nothing called the “static” keyword. So, if we want to achieve the functionality of static member functions, we USE the companion objects. This is also referred to as Object Extension. 

We must use the companion keyword in front of the object definition to construct a companion object.

// Syntax in KOTLINclass CompanionClass { companion object CompanionObjectName { // code }}val obj = CompanionClass.CompanionObjectName

We can also remove the CompanionObject name and replace it with the term companion, resulting in the companion object's default name being Companion, as SHOWN below:

// KOTLINclass CompanionClass { companion object { // code }}val obj = CompanionClass.Companion

All the required static member functions and member variables can be kept INSIDE the companion object created. For example,

class Sample { companion object Test { var a: Int = 1 fun testFunction() = println("Companion Object’s Member FUNCTION called.") }}fun main(args: Array<String>) { println(Sample.a) Sample.testFunction()}

Output:-

1Companion Object’s Member function called.


Discussion

No Comment Found