- 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.
推薦閱讀
- SQL Server 從入門到項目實踐(超值版)
- 大學計算機應用基礎實踐教程
- SQL學習指南(第3版)
- Mastering Ember.js
- Learning Data Mining with Python
- concrete5 Cookbook
- RabbitMQ Cookbook
- 移動界面(Web/App)Photoshop UI設計十全大補
- Tableau 10 Bootcamp
- Unity 3D/2D移動開發實戰教程
- 匯編語言編程基礎:基于LoongArch
- Django 3.0入門與實踐
- Geospatial Development By Example with Python
- C語言程序設計習題與實驗指導
- Solutions Architect's Handbook