August 2018
Beginner
178 pages
4h 56m
English
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 {
Read now
Unlock full access