object & companion object (Kotlin)
The object keyword declares a singleton — a class with exactly one instance. A companion object is a singleton tied to a class, holding factory methods and constants like static members in Java.
Kotlin
object Logger { ... } defines a thread-safe singleton created lazily on first use; you call its members directly as Logger.log(). Object expressions (object : Listener { ... }) create one-off anonymous instances, like Java anonymous classes.
Kotlin has no static keyword. Instead, a companion object inside a class holds members that belong to the class rather than instances: companion object { fun create() = ... }. You access them as ClassName.create(), and they're the idiomatic home for factory functions and constants.
Because a companion object is a real object, it can implement interfaces and have a name, unlike Java statics. Use object for singletons and stateless helpers, and companion object for class-level factories and constants.
Syntax
class User private constructor(val name: String) {
companion object {
fun create(n: String) = User(n)
}
}Examples
Kotlin
class Circle(val r: Double) {
companion object {
const val PI = 3.14
fun unit() = Circle(1.0)
}
}
println(Circle.PI)
println(Circle.unit().r)Output:
3.14
1.0