Object declarations

An object can also have a name. This kind of object is called an object declaration:

object Oven {
fun process(product: Bakeable) {
println(product.bake())
}
}

fun main(args: Array<String>) {
val myAlmondCupcake = Cupcake("Almond")
Oven.process(myAlmondCupcake)
}

Objects are singletons; you don't need to instantiate Oven to use it. Objects also can extend other types:

interface Oven {
fun process(product: Bakeable)
}

object ElectricOven: Oven {
override fun process(product: Bakeable) {
println(product.bake())
}
}

fun main(args: Array<String>) {
val myAlmondCupcake = Cupcake("Almond")
ElectricOven.process(myAlmondCupcake)
}
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.117.99.71