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

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.

主站蜘蛛池模板: 乌兰察布市| 洪雅县| 汝阳县| 陵川县| 汤原县| 页游| 鸡泽县| 江达县| 油尖旺区| 左权县| 法库县| 禄丰县| 靖安县| 塘沽区| 金沙县| 明溪县| 辽宁省| 巴南区| 义乌市| 宣威市| 肥城市| 佛教| 吴川市| 怀来县| 永泰县| 天柱县| 明溪县| 上犹县| 遵义市| 英超| 沈阳市| 凉城县| 灵宝市| 辰溪县| 河源市| 永寿县| 昌江| 桦南县| 巴彦淖尔市| 鄱阳县| 塔河县|