Object keyword
Kotlin has an object
keyword, which combines both declaring a class and creating an instance of it in one action. It can be used in three different situations and has three different meanings. Let's take a look at all of them:
- Object declaration: Defines a singleton class.
- Companion object: Defines a nested class that can hold members related to the outer containing class. These members can't require an instance of the outer class.
- Object expression: Creates an instance of the object on the fly, the same as Java's anonymous inner classes.
Singletons with object keyword
Sometimes, your program has to have only one instance of a certain type. This pattern is known as a singleton. In other languages, you would have to implement this pattern manually, making sure that only one instance of your type gets created. But, Kotlin has language support for creating singletons with the object keyword. Here is an example:
object Singleton { fun sayMyName() { println("I'm a singleton") }...