Sometimes we need to create an object of a slight modification of some class, without explicitly declaring a new subclass for it. Java handles this case with anonymous inner classes. Kotlin slightly generalizes this concept with object expressions and object declarations.
To create an object of an anonymous class that inherits from some type (or types), one writes:
If a supertype has a constructor, appropriate constructor parameters must be passed to it. Many supertypes may be specified as a comma-separated list after the colon:
If, by any chance, we need "just an object", with no nontrivial supertypes, we can simply say:
This is called an object declaration. If there's a name following the object keyword, we are not talking about an expression any more. We cannot assign such a thing to a variable, but we can refer to it by its name. Such objects can have supertypes:
There is one important semantical difference between object expressions and object declarations:
- object declarations are initialized lazily, when accessed for the first time
- object expressions are executed (and initialized) immediately, where they are used