- 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.
推薦閱讀
- Mastering Concurrency Programming with Java 8
- 青少年軟件編程基礎與實戰(圖形化編程三級)
- Python Deep Learning
- Learning SQLite for iOS
- 薛定宇教授大講堂(卷Ⅳ):MATLAB最優化計算
- Mastering Swift 2
- HTML5 and CSS3 Transition,Transformation,and Animation
- Web程序設計(第二版)
- 精通網絡視頻核心開發技術
- Mastering Apache Spark 2.x(Second Edition)
- D3.js 4.x Data Visualization(Third Edition)
- OpenStack Networking Essentials
- Python 3 Object:oriented Programming(Second Edition)
- 多媒體技術及應用
- Applied Deep Learning with Python