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

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.

主站蜘蛛池模板: 汨罗市| 通化市| 鞍山市| 义马市| 广灵县| 华容县| 周至县| 青浦区| 富平县| 舟山市| 华蓥市| 天津市| 佳木斯市| 手机| 建平县| 德保县| 土默特右旗| 察雅县| 洱源县| 霍城县| 那坡县| 南充市| 江油市| 天水市| 大名县| 特克斯县| 洛扎县| 荔波县| 丰顺县| 罗甸县| 东莞市| 五指山市| 沅陵县| 吉安市| 睢宁县| 隆安县| 土默特左旗| 库伦旗| 宜良县| 木兰县| 疏附县|