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.
We discussed theobjectkeyword earlier, in the sectionSingletons. Now, we'll look at another 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 keywordcompanion.
This object has its own set of functions. What's the benefit of this? You may wonder.
Just like a Java Static method, calling acompanionobject 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:
Acompanionobject may have a name-Parser, for example. But this is only for clarity of what the goal of this object is.
The class may have only onecompanionobject.
By using acompanionobject, 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.