February 2018
Intermediate to advanced
350 pages
7h 35m
English
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 ...
Read now
Unlock full access