August 2018
Beginner
178 pages
4h 56m
English
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") }}
This will both declare a Singleton class and create an instance of it. Notice how we haven't defined a constructor. Since the compiler creates an instance for you, if you tried to declare a constructor or create an instance yourself, you'd get a compiler error:
//compiler errorval singleton = Singleton ...
Read now
Unlock full access