Companion Object in Kotlin

Pandiyan Mani
2 min readFeb 23, 2023

--

In Kotlin or any other programming language such as java or c#, we used to call the method or member of a class by creating an object for that class. By using that object we access the member or method of a class. So lets see the usual method of accessing the member of class with an example.


fun main() {
var obj= A()
obj.getName()
}

class A {
var a =10;
fun getName() {
println("Value Of a $a")
}
}

In the above example we created an object for the class A as obj with that object obj we are calling the member of the class A as obj.getName()

So usually in Java we have a keyword call static in order to access member of class directly without creating any object of the specific class. Let see how we do it in java with an example



class HelloWorld {
public static void main(String[] args) {
A.getName();
}
}

class A {
static int a =10;
public static void getName() {
System.out.println("Value Of a "+a);
}
}

So you can see on above example that we use static keyword before member or method of an class. Now we can directly access member of the class without creating any object of the class.

Let see the same example in Kotlin. so in kotlin we use companion object for accessing member of the class directly without creating any object o the specific class.


fun main() {
A.getName()
}

class A {
companion object {
var a =10;
fun getName() {
println("Value Of a $a")
}
}

}

So in above example we can access directly the member of an class without creating an object.

So that all folks Happy Coding….

--

--

No responses yet