Object expressions and declarations
Sometimes you need to create an object of a slight modification of some class, without explicitly declaring a new subclass for it. Kotlin handles this case with object expressions and object declarations.
To create an object of an anonymous class that inherits from some type (or types), write:
If a supertype has a constructor, appropriate constructor parameters must be passed to it. Many supertypes can be specified as a comma-delimited list after the colon:
If you need just an object, with no nontrivial supertypes, write:
Note that anonymous objects can be used as types only in local and private declarations. If you use an anonymous object as a return type of a public function or the type of a public property, the actual type of that function or property will be the declared supertype of the anonymous object, or
Any if you haven't declared any supertype. Members added in the anonymous object will not be accessible.
The code in object expressions can access variables from the enclosing scope.
Singleton can be useful in several cases, and Kotlin (after Scala) makes it easy to declare singletons:
This is called an object declaration, and it always has a name following the
object keyword. Just like a variable declaration, an object declaration is not an expression, and cannot be used on the right hand side of an assignment statement.
Object declaration's initialization is thread-safe and done at first access.
To refer to the object, use its name directly:
Such objects can have supertypes:
An object declaration inside a class can be marked with the
Members of the companion object can be called by using simply the class name as the qualifier:
The name of the companion object can be omitted, in which case the name
Companion will be used:
The name of a class used by itself (not as a qualifier to another name) acts as a reference to the companion object of the class (whether named or not):
Note that, even though the members of companion objects look like static members in other languages, at runtime those are still instance members of real objects, and can, for example, implement interfaces:
However, on the JVM you can have members of companion objects generated as real static methods and fields, if you use the
@JvmStatic annotation. See the Java interoperability section for more details.
Semantic difference between object expressions and declarations
There is one important semantic difference between object expressions and object declarations:
Object expressions are executed (and initialized) immediately, where they are used.
Object declarations are initialized lazily, when accessed for the first time.
A companion object is initialized when the corresponding class is loaded (resolved), matching the semantics of a Java static initializer.