Object declarations

Unlike object expressions, object declarations have a name and cannot be passed into a variable, method argument, and so on, or declared locally. They can be referred by their name and used anywhere within the scope for which they are declared. This is shown with the following code example:

object BeanRegister {
fun registerBean(bean: Any) {
println("$bean is registered");
}
}

The declared BeanRegister object at the top level will become a singleton class and its initialization is thread-safe. It can be used as follows:

BeanRegister.registerBean("String bean");

As with the preceding code, the object's declared name must be used to invoke the methods inside the object declaration. Object declarations are lazily initialized and executed the first time they are called. Object declarations can also have an associated type, like in the following code:

object PettableSingleton : Pettable {
override fun play() {
super.play()
}
}
..................Content has been hidden....................

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