Careeroza
Object Declarations (Singletons)
One Instance Only
An object declaration defines a class and creates its single instance at the same time. It is created lazily on first use and is thread-safe. Use it for things the whole app shares: a logger, a config, an in-memory cache.
Example
object AppSession {
var userName: String? = null
private var loginCount = 0
fun login(name: String) {
userName = name
loginCount++
println("Logged in as $name (login #$loginCount)")
}
}
fun main() {
AppSession.login("Asha")
AppSession.login("Ravi")
println(AppSession.userName)
println(AppSession === AppSession) // always the same object
}Output
Logged in as Asha (login #1) Logged in as Ravi (login #2) Ravi true
Objects Can Inherit
Example
interface Comparator2<T> { fun compare(a: T, b: T): Int }
object ByLength : Comparator2<String> {
override fun compare(a: String, b: String) = a.length - b.length
}
fun main() {
val words = listOf("banana", "kiwi", "apple")
println(words.sortedWith { a, b -> ByLength.compare(a, b) })
}Output
[kiwi, apple, banana]
Note: Avoid storing mutable global state in objects in large apps - it makes testing hard. For shared services, dependency injection (Hilt/Koin) usually provides the single instance instead.