An object declaration uses Kotlin’s object keyword to define a class and create its single instance in one statement. Use it when one shared instance is the natural model: a payroll registry, a stateless comparator, or another singleton service. It replaces the Java-style singleton setup of a private constructor plus a static instance field. section 4.4.1 section 4.2.1
A singleton comparator
object CaseInsensitiveFileComparator : Comparator<File> { override fun compare(file1: File, file2: File): Int = file1.path.compareTo(file2.path, ignoreCase = true) } val files = listOf(File("/Z"), File("/a")) println(files.sortedWith(CaseInsensitiveFileComparator)) // [/a, /Z] The declaration names both the class and its sole instance. Call members through that name; no constructor call is needed. Implementing Comparator is useful here because this comparison strategy normally has no per-instance state. section 4.4.1
An object declaration behaves like a class in several important ways:
- It can declare properties, functions, initializer blocks, and other members. section 4.4.1
- It can inherit from a class or implement an interface, allowing a single reusable implementation of a required contract. section 4.4.1
- It cannot declare primary or secondary constructors; provide initial state in the object body instead. section 4.4.1
- It is created immediately at its definition rather than instantiated elsewhere. section 4.4.1
A nested object can keep a singleton close to the type it serves. For example, Person.NameComparator can compare Person values by name and be passed directly to sortedWith. This is still an object declaration, not an instance member of Person. section 4.4.1
Do not confuse a plain object declaration with a companion object or an object expression. A companion object is an object declaration inside a class whose members may be reached through the class name, often for factory methods that need private-constructor access. An object expression fills the role of a Java anonymous inner class. section 4.4 section 4.4.2
For Java callers, Kotlin object declarations expose the singleton through an INSTANCE field, such as CaseInsensitiveFileComparator.INSTANCE. Kotlin code normally uses the shorter object name directly. section 4.4.1
