Bird
Raised Fist0
Kotlinprogramming~10 mins

Why object declarations create singletons in Kotlin - Visual Breakdown

Choose your learning style10 modes available
Concept Flow - Why object declarations create singletons
Start program
↓
Declare object
↓
Object instance created once
↓
Access object multiple times
↓
Same instance used every time
↓
Program ends
The program declares an object which creates a single instance. Every access uses this same instance, ensuring only one exists.
Execution Sample
Kotlin
object Logger {
    fun log(msg: String) = println("Log: $msg")
}

fun main() {
    Logger.log("Start")
    Logger.log("End")
}
This code declares a singleton object Logger and calls its log function twice, using the same instance.
Execution Table
StepActionEvaluationResult
1Program startsNo object instance yetNo instance created
2Object Logger declaredObject declaration does not immediately create instanceInstance created at first access
3Call Logger.log("Start")Instance created at first access, then usedPrints: Log: Start
4Call Logger.log("End")Use same Logger instancePrints: Log: End
5Program endsNo new instances createdOnly one Logger instance used
💡 Program ends after using the single Logger instance multiple times
Variable Tracker
VariableStartAfter Step 2After Step 3After Step 4Final
Logger instancenullnullcreatedusedused
Key Moments - 3 Insights
Why is the Logger instance created only once?
Because object declarations in Kotlin create a singleton instance at first access, as shown in execution_table step 3.
Does calling Logger.log create a new Logger instance each time?
No, the same Logger instance is reused every time, as shown in steps 3 and 4 of the execution_table.
What if we declare Logger as a class instead of object?
Then each time we create Logger(), a new instance is made. But with object, Kotlin ensures only one instance exists.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table, at which step is the Logger instance created?
AStep 1
BStep 3
CStep 2
DStep 4
💡 Hint
Check the 'Result' column in execution_table row for Step 3
According to variable_tracker, what is the state of Logger instance after Step 4?
Anull
Bcreated
Cused
Ddestroyed
💡 Hint
Look at the 'Logger instance' row and the 'After Step 4' column in variable_tracker
If Logger was declared as a class, how would the execution_table change?
AInstance created at every call to log()
BInstance created once at Step 2
CNo instance created
DInstance created only at program end
💡 Hint
Recall that class declarations create new instances on each constructor call, unlike object declarations
Concept Snapshot
Kotlin object declarations create a singleton instance.
This instance is created once at first access.
All uses share the same instance.
Use object for single-instance utilities.
Unlike classes, no new instances are made on usage.
Full Transcript
In Kotlin, when you declare an object, the system creates exactly one instance of it. This instance is made the first time the object is accessed. Every time you use the object later, you get the same instance. For example, the Logger object is created once when the program starts. When Logger.log is called twice, both calls use the same Logger instance. This is different from classes, where each new object is a new instance. Objects are useful when you want a single shared instance, like for logging or configuration.

Practice

(1/5)
1. Why does an object declaration in Kotlin create a singleton?
easy
A. Because it cannot hold any properties or functions
B. Because it allows multiple instances to be created
C. Because it is the same as a class with a constructor
D. Because it creates only one instance automatically and shares it everywhere

Solution

  1. Step 1: Understand object declaration behavior

    An object declaration creates a single instance automatically without needing to call a constructor.
  2. Step 2: Recognize singleton sharing

    This single instance is shared everywhere in the program, ensuring only one copy exists.
  3. Final Answer:

    Because it creates only one instance automatically and shares it everywhere -> Option D
  4. Quick Check:

    Singleton = single shared instance [OK]
Hint: Object declarations create one shared instance automatically [OK]
Common Mistakes:
  • Thinking object creates multiple instances
  • Confusing object with regular class
  • Assuming object cannot have properties
2. Which of the following is the correct syntax to declare a singleton object in Kotlin?
easy
A. object MySingleton { fun greet() = "Hello" }
B. class MySingleton() { fun greet() = "Hello" }
C. singleton MySingleton { fun greet() = "Hello" }
D. object MySingleton() { fun greet() = "Hello" }

Solution

  1. Step 1: Identify correct object declaration syntax

    In Kotlin, object declarations do not use parentheses; they are declared as object Name { ... }.
  2. Step 2: Check options for syntax errors

    object MySingleton { fun greet() = "Hello" } uses correct syntax without parentheses. object MySingleton() { fun greet() = "Hello" } incorrectly uses parentheses. Options B and C use invalid keywords or class syntax.
  3. Final Answer:

    object MySingleton { fun greet() = "Hello" } -> Option A
  4. Quick Check:

    Object declaration syntax = object Name { } [OK]
Hint: Object declarations never have parentheses after the name [OK]
Common Mistakes:
  • Adding parentheses after object name
  • Using class keyword instead of object
  • Using non-existent singleton keyword
3. What will be the output of this Kotlin code?
object Counter {
    var count = 0
    fun increment() { count++ }
}

fun main() {
    Counter.increment()
    Counter.increment()
    println(Counter.count)
}
medium
A. 0
B. 1
C. 2
D. Compilation error

Solution

  1. Step 1: Understand the singleton object usage

    The Counter object holds a single count variable shared everywhere. Calling increment() increases count by 1 each time.
  2. Step 2: Trace the increments and print

    Two calls to increment() increase count from 0 to 2. Printing Counter.count outputs 2.
  3. Final Answer:

    2 -> Option C
  4. Quick Check:

    2 increments = count 2 [OK]
Hint: Object properties keep state shared across calls [OK]
Common Mistakes:
  • Assuming count resets each call
  • Thinking increment returns a value
  • Confusing object with class instance
4. This Kotlin code tries to create two instances of an object. What is the error?
object Logger {
    fun log(msg: String) = println(msg)
}

fun main() {
    val log1 = Logger()
    val log2 = Logger()
    log1.log("Test")
}
medium
A. log1 and log2 are null
B. Cannot create instances of an object; it has no constructor
C. Logger object is missing a constructor
D. No error; code runs fine

Solution

  1. Step 1: Understand object instantiation rules

    In Kotlin, object declarations cannot be instantiated with parentheses because they have no constructor and are singletons.
  2. Step 2: Identify the error in code

    Trying to call Logger() causes a compilation error because object cannot be instantiated.
  3. Final Answer:

    Cannot create instances of an object; it has no constructor -> Option B
  4. Quick Check:

    Object cannot be instantiated = error [OK]
Hint: Objects have no constructors; don't use parentheses [OK]
Common Mistakes:
  • Trying to instantiate object with ()
  • Assuming object needs constructor
  • Ignoring compilation errors
5. You want to count how many times a function is called across your entire Kotlin program. Which approach using an object declaration is best?
hard
A. Declare an object with a mutable counter property and increment it inside the function
B. Declare a class with a counter property and create a new instance each call
C. Use a local variable inside the function to count calls
D. Declare an object with a constant counter property initialized to zero

Solution

  1. Step 1: Identify need for shared mutable state

    Counting calls across the program requires a shared variable that updates each time the function runs.
  2. Step 2: Choose object with mutable property

    An object with a mutable counter property can be accessed and incremented from anywhere, preserving state.
  3. Step 3: Evaluate other options

    Creating new class instances each call resets count. Local variables reset each call. Constant properties cannot change.
  4. Final Answer:

    Declare an object with a mutable counter property and increment it inside the function -> Option A
  5. Quick Check:

    Singleton object with mutable state counts calls [OK]
Hint: Use object with var property to share and update count [OK]
Common Mistakes:
  • Using class instances that reset count
  • Using val instead of var for counter
  • Counting inside local function variable
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard