The object Keyword
Most likely, there have been developers over the years who have wondered why object-oriented programming languages do not have any sort of object
keyword.
The designers of Kotlin may have been among those developers, as they have given Kotlin such an object
keyword. This gets used in a few different places in Kotlin syntax
Singletons
One way to declare singletons in Kotlin is to use a top-level val
declaration:
class Transmogrifier {
fun transmogrify() {
println("Presto, change-o!")
}
}
val QUASI_SINGLETON = Transmogrifier()
fun main() {
QUASI_SINGLETON.transmogrify()
}
In truth, though, we can have as many instances of Transmogrifier
as we want. QUASI_SINGLETON
is merely a global instance of Transmogrifier
. We cannot prevent others from making their own Transmogrifier
instances, as then we could not create the quasi-singleton. For example, we cannot make the constructor be private
, like this:
class Transmogrifier private constructor() {
fun transmogrify() {
// TODO
}
}
val QUASI_SINGLETON = Transmogrifier()
QUASI_SINGLETON.transmogrify()
as that results in a compile error:
error: cannot access '<init>': it is private in 'Transmogrifier'
val QUASI_SINGLETON = Transmogrifier()
^
To create a true singleton, all we need to do is:
- Replace the
class
withobject
- Call functions on that
object
based on its name, rather than creating some instance ourselves
object Transmogrifier {
fun transmogrify() {
println("Presto, change-o!")
}
}
fun main() {
Transmogrifier.transmogrify()
}
An object
declared this way can have properties and functions like a regular class. It cannot have a constructor, which makes sense, since there will only ever be one instance. However, if it extends classes, it can (and must) call the superclass constructors:
open class Base {
// TODO stuff here
}
object Transmogrifier : Base() {
fun transmogrify() {
println("Presto, change-o!")
}
}
fun main() {
Transmogrifier.transmogrify()
}
As with singletons in any programming environment, though, the ones that we declare via object
will live for the life of our process, so be careful that you are not creating a memory leak by having an object
hold onto more and more stuff over time.
Prev Table of Contents Next
This book is licensed under the Creative Commons Attribution-ShareAlike 4.0 International license.