← Back to Kotlin Course | Chapter 6: Classes & Objects | Lesson 6 of 7

Object Declarations

An object declaration creates exactly one single instance of something automatically, so you never have to build it yourself.
Syntax
kotlin
object ObjectName {
    val property: Type = value
    fun method() { }
}

ObjectName.property
ObjectName.method()

Declaring a Singleton

object Name { ... } defines both the class and its single instance at once; there is no separate constructor call -- you simply refer to Name directly to use it.

Example: Declaring a Singleton

markup
// Define the singleton object `AppConfig`
object AppConfig {
    // Declare a read-only variable `appName`, set to `"MyApp"`
    val appName = "MyApp"
    // Declare a mutable variable `debugMode`, initialized to `false`
    var debugMode = false
}

// Entry point: execution of the program starts here
fun main() {
    // Print `AppConfig.appName` to the console, with a trailing newline
    println(AppConfig.appName)
    AppConfig.debugMode = true
    // Print "Debug: ${AppConfig.debugMode}" to the console, with a trailing newline
    println("Debug: ${AppConfig.debugMode}")
}

Object Declarations for Utility Functions

Objects are a natural place for stateless utility functions that logically belong together but don't need an instance per call.

Example: Object Declarations for Utility Functions

markup
// Define the singleton object `MathUtils`
object MathUtils {
    fun square(x: Int) = x * x
    fun cube(x: Int) = x * x * x
}

// Entry point: execution of the program starts here
fun main() {
    // Print "Square of 5: ${MathUtils.square(5)}" to the console, with a trailing newline
    println("Square of 5: ${MathUtils.square(5)}")
    // Print "Cube of 3: ${MathUtils.cube(3)}" to the console, with a trailing newline
    println("Cube of 3: ${MathUtils.cube(3)}")
}

Lazy Initialization

An object's instance is created the first time it is accessed, not necessarily when the program starts, which can be observed by printing from its own init block.

Example: Lazy Initialization

markup
// Define the singleton object `Session`
object Session {
    init {
        // Print "Session object created" to the console, with a trailing newline
        println("Session object created")
    }
    // Declare a read-only variable `id`, set to `"abc123"`
    val id = "abc123"
}

// Entry point: execution of the program starts here
fun main() {
    // Print "Before accessing Session" to the console, with a trailing newline
    println("Before accessing Session")
    // Print "Session id: ${Session.id}" to the console, with a trailing newline
    println("Session id: ${Session.id}")
}

Object Expressions for One-Off Instances

An anonymous object : Type { ... } creates a single-use instance implementing an interface or extending a class, useful for a quick, throwaway implementation without declaring a full named class.

Example: Object Expressions for One-Off Instances

markup
// Define an interface `ClickListener` describing required behavior
interface ClickListener {
    // Define the function `onClick` with no parameters
    fun onClick()
}

// Entry point: execution of the program starts here
fun main() {
    // Call `object : ClickListener` with a trailing lambda, storing the result in `listener`
    val listener = object : ClickListener {
        override fun onClick() {
            // Print "Clicked!" to the console, with a trailing newline
            println("Clicked!")
        }
    }
    listener.onClick()
}
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the view already swaps in the hi_ translation fields (or blanks these out if untranslated), so this renders correctly for both languages without a lang_code check here. #}
Common Mistakes
  1. Trying to pass constructor arguments to an object declaration; singletons declared with object cannot take constructor parameters.
  2. Forgetting an object is lazily initialized on first access, not at program startup, which can matter for side effects in its init block.
  3. Confusing object declarations (named singletons) with anonymous object expressions used for one-off implementations.
Chapter Summary
  • object Name { ... } declares a singleton -- exactly one instance that is created lazily on first access.
  • Singletons cannot have constructor parameters since there is no explicit call to create them.
  • An anonymous object : SomeType { ... } (an object expression) creates a one-off instance implementing an interface or extending a class, often used where a Java anonymous class would be used.
  • Object declarations are commonly used for utility functions, constants, and shared state that should exist exactly once.
🔒

Chapter Quiz — Complete all 7 topics to unlock

0/7 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.