Anonymous objects

The object keyword has one more use, creating anonymous objects. If you are familiar with Java, then you probably had experience with anonymous inner classes. Anonymous objects are similar to them. With them, you create objects on the fly. Let's create an anonymous object of a Runnable interface:

Thread(object : Runnable {
override fun run() {
println("I'm created with anonymous object")
}
}).run()

The syntax for creating anonymous objects is similar to singleton objects, but without the name of the object. The name in most cases is not needed. If you need a name for your anonymous object, or need it to store for later use, you can initialize a variable with it. This example shows it:

val runnable = object : Runnable {
override fun run() {
println("I'm created with anonymous object")
}
}

Anonymous objects are not restricted to interfaces, you can also create classes with them. Here's how you would create an anonymous object of an abstract class. Notice how we had to call the constructor of the class:

val writer = object : Writer() {

override fun write(cbuf: CharArray, off: Int, len: Int) {
// implementation omitted
}

override fun flush() {
// implementation omitted
}

override fun close() {
// implementation omitted
}
}
..................Content has been hidden....................

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