官术网_书友最值得收藏!

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.

主站蜘蛛池模板: 东乡县| 大名县| 香河县| 酒泉市| 泰顺县| 盘山县| 镇雄县| 马边| 新平| 陆河县| 衡南县| 巩义市| 曲麻莱县| 宾阳县| 玉山县| 宁海县| 新河县| 会昌县| 通辽市| 保山市| 南宁市| 馆陶县| 呼和浩特市| 孟津县| 板桥市| 吴忠市| 南昌市| 武乡县| 曲阜市| 临澧县| 安塞县| 辉县市| 凤冈县| 泽库县| 遵义县| 吴旗县| 徐闻县| 璧山县| 犍为县| 阜康市| 台湾省|