Static Factory Method in Kotlin

We've already discussed the object keyword earlier in the Singleton section. Now we'll see another use of it is a companion object.

In Java, Static Factory Methods are declared static. But in Kotlin, there's no such keyword. Instead, methods that don't belong to an instance of a class can be declared inside a companion object:

class NumberMaster {
companion object {
fun valueOf(hopefullyNumber: String) : Long {
return hopefullyNumber.toLong()
}
}
}
Companion objects may have a name: companion object Parser, for example. But this is only for clarity of what the goal of this object is.

Calling a companion object doesn't require instantiating a class:

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

Moreover, calling it on an instance of a class simply won't work, unlike Java:

println(NumberMaster().valueOf("123")) // Won't compile
The class may have only one companion object.
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.216.77.153