June 2018
Intermediate to advanced
310 pages
6h 32m
English
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() } }}
Calling a companion object doesn't require instantiating a class:
println(NumberMaster.valueOf("123")) // Prints 123
Moreover, ...
Read now
Unlock full access