object Declaration: Kotlin Singletons
Create singletons with object and understand their lifecycle.
object as a Singleton
An object declaration creates a single instance — a thread-safe, lazily-initialized singleton — with one line of code.
Declaring a Singleton
Use object Name { ... } to declare a singleton with state and methods.
object Logger {
fun log(msg: String) = println("[LOG] $msg")
}
fun main() {
Logger.log("App started")
Logger.log("User signed in")
}All lessons in this course
- object Declaration: Kotlin Singletons
- companion object: Static-like Members in Kotlin
- Anonymous Objects and Object Expressions
- Factory Methods with companion object