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

  • Functional Kotlin
  • Mario Arias Rivu Chakraborty
  • 245字
  • 2021-06-24 19:15:22

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.

主站蜘蛛池模板: 巴马| 招远市| 台湾省| 延长县| 芜湖市| 皋兰县| 玉溪市| 台中县| 饶河县| 临西县| 西丰县| 平阴县| 常熟市| 曲阜市| 河南省| 英吉沙县| 洱源县| 滨海县| 乌鲁木齐县| 女性| 杭州市| 霸州市| 大名县| 霍城县| 讷河市| 克什克腾旗| 巴南区| 汝州市| 泸西县| 西宁市| 浦北县| 城步| 桑日县| 车致| 禄丰县| 屏山县| 邢台县| 新安县| 新建县| 铜鼓县| 连平县|