Updated:
The object keyword creates a class and its single instance at the same time. Kotlin uses it in three ways: object declarations (singletons), companion objects (members tied to a class instead of an instance), and object expressions (one-off anonymous objects).
Object declaration: a singleton
A singleton is a class with exactly one instance, shared by the whole app:
object AppConfig {
val baseUrl = "https://api.example.com"
var darkMode = false
fun summary() = "url=$baseUrl, darkMode=$darkMode"
}
fun main() {
println(AppConfig.summary())
AppConfig.darkMode = true
println(AppConfig.summary())
}Output:
url=https://api.example.com, darkMode=false url=https://api.example.com, darkMode=true
You don’t create it with a constructor. You just use its name. It’s created the first time it’s used, and creation is thread-safe.
A singleton with state
object Cart {
private val items = mutableListOf<String>()
fun add(item: String) { items.add(item) }
fun count() = items.size
}
fun addFromHome() = Cart.add("Mouse")
fun addFromSearch() = Cart.add("Keyboard")
fun main() {
addFromHome()
addFromSearch()
println(Cart.count()) // both functions used the same Cart
}Output:
2
Use mutable singletons sparingly. Global state makes code harder to test. In Android apps, a dependency injection library (such as Hilt) usually manages single instances instead.
Companion object
A companion object lives inside a class. Its members are called on the class name, like Java’s static members:
class User private constructor(val name: String, val isGuest: Boolean) {
companion object {
const val MAX_NAME_LENGTH = 20
fun create(name: String) = User(name.take(MAX_NAME_LENGTH), isGuest = false)
fun guest() = User("Guest", isGuest = true)
}
}
fun main() {
val a = User.create("Meera")
val g = User.guest()
println("${a.name} guest=${a.isGuest}")
println("${g.name} guest=${g.isGuest}")
println(User.MAX_NAME_LENGTH)
}Output:
Meera guest=false Guest guest=true 20
Common uses for companion objects:
- Factory functions like
create(),fromJson()ornewInstance(), often together with a private constructor. - Constants with
const val, such as keys, limits and tags.
Constants: const val
class PrefsKeys {
companion object {
const val THEME = "theme"
const val LANGUAGE = "language"
}
}
object Limits {
const val MAX_UPLOAD_MB = 25
}
fun main() {
println(PrefsKeys.THEME)
println("Max upload: ${Limits.MAX_UPLOAD_MB} MB")
}Output:
theme Max upload: 25 MB
Object expressions: one-off objects
An object expression creates an anonymous object on the spot, often to implement an interface just once:
interface ClickListener { fun onClick(id: Int) }
fun setListener(listener: ClickListener) {
listener.onClick(7)
}
fun main() {
var clicks = 0
setListener(object : ClickListener {
override fun onClick(id: Int) {
clicks++
println("Clicked item $id")
}
})
println("Total clicks: $clicks")
}Output:
Clicked item 7 Total clicks: 1
If the interface has a single function and is declared as a fun interface, a lambda is shorter: setListener { id -> … }.
Companion objects can implement interfaces
interface Parser<T> { fun parse(text: String): T }
data class Point(val x: Int, val y: Int) {
companion object : Parser<Point> {
override fun parse(text: String): Point {
val (x, y) = text.split(",").map { it.trim().toInt() }
return Point(x, y)
}
}
}
fun main() {
println(Point.parse("3, 4"))
}Output:
Point(x=3, y=4)
Calling from Java: @JvmStatic
From Kotlin, you call User.create(...). From Java, the default is User.Companion.create(...). Add @JvmStatic to the function to call it as User.create(...) from Java too. This only matters when Java code uses your class.
Comparison
| Object declaration | Companion object | Object expression | |
|---|---|---|---|
| Written as | object Name { } | companion object { } inside a class | object : Type { } in an expression |
| Instances | one, app-wide | one per class | a new one each time |
| Typical use | config, registries, utilities | factories, constants | one-off listeners and callbacks |
Common mistakes
- Trying to call a constructor:
AppConfig()doesn’t compile; an object has no constructor. - Putting everything in a companion object: if a function doesn’t need the class’s private members, a top-level function is simpler.
- Using
valinstead ofconst valfor constants:constis inlined at compile time, but it only works for primitives andString.
Exercise
Create an IdGenerator singleton that hands out unique IDs with a prefix, and a Ticket class whose companion object uses it.
object IdGenerator {
private var next = 1
fun nextId(prefix: String) = "$prefix-${next++}"
}
class Ticket private constructor(val id: String, val title: String) {
companion object {
fun open(title: String) = Ticket(IdGenerator.nextId("TKT"), title)
}
override fun toString() = "$id: $title"
}
fun main() {
println(Ticket.open("Login page broken"))
println(Ticket.open("Add dark mode"))
println(Ticket.open("Typo on pricing page"))
}Output:
TKT-1: Login page broken TKT-2: Add dark mode TKT-3: Typo on pricing page
FAQ
What is an object in Kotlin?
A class with exactly one instance, declared with object Name { }. It’s Kotlin’s built-in way to make a singleton.
What is a companion object in Kotlin?
An object inside a class whose members you call on the class name, like User.create(). It replaces Java’s static members.
Is a Kotlin object thread-safe?
Its creation is. The object is created once, safely, the first time it’s used. Changing its state from several threads still needs care.
Keep reading



