Object expressions

An object expression can be used to create objects without the need to have a class declaration for them. For example, the Lion class from previous sections does not implement the Pettable interface. This doesn't mean that there can't be extreme cases where exotic tamed animals can be used as pets. So, a one time tamed Lion instance can be created on the fly as follows:

var tamedLionPet = object : Lion("roar"), Pettable {
override fun name() : String {
return "Tamed Pet Lion";
}
}

Using the object keyword, a class of Lion that implements the Pettable interface can be created and an instance can be created out of it for a single use. Also with this, a class is not even required to create an object. This can be explained by the following code:

var personObjectWithoutAClass = object {
var name : String = "Shazin"
var age : Int = 32
}

The preceding code creates a person object with name and age without the need for a class declaration. These expressions can be passed as arguments to methods also. Object expressions are eagerly initialized and executed at the place where they are expressed.

..................Content has been hidden....................

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