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

Companion objects

Objects declared inside a class/interface can be marked as companion objects. Observe the use of companion objects in the following code:

class Cupcake(flavour: String) : BakeryGood(flavour), Bakeable {
override fun name(): String {
return "cupcake"
}

companion object {
fun almond(): Cupcake {
return Cupcake("almond")
}

fun cheese(): Cupcake {
return Cupcake("cheese")
}
}
}

Now, methods inside the companion object can be used directly, using the class name without instantiating it:

fun main(args: Array<String>) {
val myBlueberryCupcake: BakeryGood = Cupcake("Blueberry")
val myAlmondCupcake = Cupcake.almond()
val myCheeseCupcake = Cupcake.cheese()
val myCaramelCupcake = Cupcake("Caramel")
}

Companion object's methods can't be used from instances:

fun main(args: Array<String>) {
val myAlmondCupcake = Cupcake.almond()
val myCheeseCupcake = myAlmondCupcake.cheese() //Compilation error: Unresolved reference: cheese
}

Companion objects can be used outside the class as values with the name Companion:

fun main(args: Array<String>) {
val factory: Cupcake.Companion = Cupcake.Companion
}

Alternatively, a Companion object can have a name:

class Cupcake(flavour: String) : BakeryGood(flavour), Bakeable {
override fun name(): String {
return "cupcake"
}

companion object Factory {
fun almond(): Cupcake {
return Cupcake("almond")
}

fun cheese(): Cupcake {
return Cupcake("cheese")
}
}
}

fun main(args: Array<String>) {
val factory: Cupcake.Factory = Cupcake.Factory
}

They can also be used without a name, as shown in the following code:

fun main(args: Array<String>) {
val factory: Cupcake.Factory = Cupcake
}

Don't be confused by this syntax. The Cupcake value without parenthesis is the companion object; Cupcake() is an instance.

主站蜘蛛池模板: 青河县| 赞皇县| 扶余县| 昌邑市| 长治市| 正阳县| 乌拉特后旗| 巢湖市| 嘉善县| 鲜城| 衡阳县| 绥棱县| 获嘉县| 漾濞| 安阳县| 田林县| 明星| 建湖县| 綦江县| 凉城县| 含山县| 泰兴市| 钟祥市| 望谟县| 宝兴县| 海宁市| 嘉善县| 微博| 克拉玛依市| 万荣县| 嘉定区| 乌兰浩特市| 西青区| 吐鲁番市| 金昌市| 万州区| 凤台县| 西丰县| 壤塘县| 大连市| 五莲县|