Part 09 / Topic 9 of 10
object declarations and companion objects
An object declares a singleton — exactly one instance, created lazily on first access,
not at program startup:
object Logger {
init { println("Logger: initialising for the first time") }
private val lines = mutableListOf<String>()
fun log(message: String) { lines += message; println("LOG: $message") }
}
Before first Logger access: nothing printed yet
Logger: initialising for the first time
LOG: server started
LOG: user signed in
Nothing prints until Logger.log(...) is called the first time — proof the init block really
does wait, rather than running at program start the way a top-level val might suggest.
A companion object attaches members to the class itself, Kotlin's answer to Java's static,
and it's the idiomatic home for a named factory function:
class User private constructor(val name: String, val username: String) {
companion object {
private var createdCount = 0
fun of(fullName: String): User {
createdCount++
val handle = fullName.trim().lowercase().replace(" ", ".")
return User(fullName.trim(), handle)
}
fun createdSoFar(): Int = createdCount
}
override fun toString(): String = "$name (@$username)"
}
Asha Verma (@asha.verma)
Ravi Kumar (@ravi.kumar)
Users created via the factory: 2
The constructor is private, so User(...) can't be called from outside the class at all —
User.of(fullName) is the only supported way to build one, and it reads better at the call site
than a constructor overload for "derive the username from the full name."
Full program: examples/08_object_and_companion.kt.
Done here? The practice set for Part 9 — including the solutions — is on the part page.