Introduction to companion object in Kotlin

In Java, Static Factory Methods are declared like this:

private static class MyClass { 
    // Don't want anybody to use it but me 
    private MyClass() { }

    // This will replace the public constructor 
    public static MyClass create() { 
        return new MyClass(); 

They are called like this:

MyClass myClass = MyClass.create(); 

But in Kotlin, there's no such keyword as static. Instead, methods that don't belong to an instance of a class can be declared inside a companion object.

Now, we'll look at use of this important keyword using the following example:

class NumberMaster { 
    companion object { 
        fun valueOf(hopefullyNumber: String) : Long { 
            return hopefullyNumber.toLong() 

As you can see, inside our class, we have declared an object that is prefixed by the keyword companion. This object has its own set of functions.

Just like a Java static method, calling a companion object doesn't require the instantiation of a class:

println(NumberMaster.valueOf("123")) // Prints 123 

Moreover, calling it on an instance of a class simply won't work, which is not the case with Java:

println(NumberMaster().valueOf("123")) // Won't compile 

The class may have only one companion object.

By using a companion object, we can achieve exactly the same behavior that we see in Java:

private class MyClass private constructor() { 
    companion object { 
        fun create(): MyClass { 
            return MyClass() 

We can now instantiate our object, as shown in the following code:

// This won't compile 
//val instance = MyClass()

// But this works as it should 
val instance = MyClass.create() 

Kotlin proves itself a very practical language. Every keyword in it has a down-to-earth meaning.