- 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.
推薦閱讀
- OpenStack Cloud Computing Cookbook(Third Edition)
- UML和模式應用(原書第3版)
- Three.js開發指南:基于WebGL和HTML5在網頁上渲染3D圖形和動畫(原書第3版)
- Learning Flask Framework
- 精通搜索分析
- Apache Karaf Cookbook
- Linux環境編程:從應用到內核
- 3D少兒游戲編程(原書第2版)
- 學Python也可以這么有趣
- 快速念咒:MySQL入門指南與進階實戰
- Web前端應用開發技術
- Python Data Science Cookbook
- Kivy Cookbook
- Buildbox 2.x Game Development
- JBoss:Developer's Guide