Bird
Raised Fist0
Kotlinprogramming~10 mins

Object expressions (anonymous objects) in Kotlin - Step-by-Step Execution

Choose your learning style10 modes available
Concept Flow - Object expressions (anonymous objects)
Start
↓
Create anonymous object
↓
Initialize properties
↓
Call methods
↓
Use object
↓
End
This flow shows how Kotlin creates an anonymous object, initializes it, and uses its properties and methods immediately.
Execution Sample
Kotlin
val obj = object {
    val x = 10
    fun greet() = "Hi"
}
println(obj.x)
println(obj.greet())
Creates an anonymous object with a property and a method, then prints them.
Execution Table
StepActionEvaluationResult
1Create anonymous objectobject { val x=10; fun greet() = "Hi" }Object created with x=10 and greet()
2Initialize property xx = 10x is set to 10
3Define method greet()fun greet() = "Hi"Method greet() ready
4Assign object to variable objval obj = object {...}obj references the anonymous object
5Call obj.xobj.x10
6Call obj.greet()obj.greet()"Hi"
💡 All properties and methods accessed; program ends.
Variable Tracker
VariableStartAfter 1After 2After 3Final
objnullobject createdx=10 setgreet() definedobj references object with x=10 and greet()
Key Moments - 2 Insights
Why can we access obj.x and obj.greet() even though the object has no class name?
Because the object expression creates an anonymous object with properties and methods accessible through the variable obj, as shown in steps 4-6 of the execution_table.
Is the anonymous object reusable or only created once?
The anonymous object is created once when assigned to obj (step 4). It is not reusable like a class but can be used via obj as long as it exists.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table, what is the value of obj.x at step 5?
Anull
B10
C"Hi"
DUndefined
💡 Hint
Check step 5 in execution_table where obj.x is called and returns 10.
At which step is the greet() method defined in the anonymous object?
AStep 2
BStep 4
CStep 3
DStep 6
💡 Hint
Look at step 3 in execution_table where greet() is defined.
If we add a new property y = 20 inside the object, which step would change?
AStep 2
BStep 3
CStep 5
DStep 6
💡 Hint
Adding a property affects initialization steps, see step 2 where x is initialized.
Concept Snapshot
Object expressions create anonymous objects on the spot.
Syntax: val obj = object { val x = 10; fun greet() = "Hi" }
Use obj.property or obj.method() to access.
No class name needed.
Good for quick, one-time objects.
Full Transcript
This example shows how Kotlin creates an anonymous object using an object expression. The object has a property x set to 10 and a method greet() returning "Hi". The object is assigned to the variable obj. We then access obj.x and obj.greet() to get 10 and "Hi" respectively. The execution table traces each step: creating the object, initializing properties, defining methods, assigning to obj, and calling members. The variable tracker shows obj starting as null and ending referencing the anonymous object. Key moments clarify why we can use obj.x and obj.greet() even without a class name, and that the object is created once. The quiz tests understanding of values at steps and effects of adding properties. The snapshot summarizes the concept simply.

Practice

(1/5)
1. What is an object expression in Kotlin?
easy
A. A named class declaration
B. A way to create an anonymous object with properties and functions
C. A function that returns a string
D. A variable declaration with a fixed value

Solution

  1. Step 1: Understand object expressions

    Object expressions create unnamed objects on the spot with properties and functions.
  2. Step 2: Differentiate from other options

    Named classes, functions, and variables are different concepts and do not create anonymous objects.
  3. Final Answer:

    A way to create an anonymous object with properties and functions -> Option B
  4. Quick Check:

    Object expression = anonymous object [OK]
Hint: Anonymous objects = quick unnamed objects [OK]
Common Mistakes:
  • Confusing object expressions with named classes
  • Thinking object expressions are functions
  • Assuming object expressions are variables
2. Which of the following is the correct syntax to create an anonymous object in Kotlin?
easy
A. val obj = object() { val x = 10 }
B. val obj = class { val x = 10 }
C. val obj = object { val x = 10 }
D. val obj = fun() { val x = 10 }

Solution

  1. Step 1: Recall Kotlin object expression syntax

    The correct syntax uses object { ... } without parentheses.
  2. Step 2: Check each option

    val obj = object { val x = 10 } matches the correct syntax. val obj = class { val x = 10 } uses class which is invalid here. val obj = fun() { val x = 10 } uses fun() which is a function, not an object. val obj = object() { val x = 10 } incorrectly adds parentheses after object.
  3. Final Answer:

    val obj = object { val x = 10 } -> Option C
  4. Quick Check:

    Correct syntax = object { ... } [OK]
Hint: Use 'object { }' without parentheses for anonymous objects [OK]
Common Mistakes:
  • Adding parentheses after 'object'
  • Using 'class' instead of 'object'
  • Confusing functions with object expressions
3. What will be the output of this Kotlin code?
val obj = object {
    val name = "Alice"
    fun greet() = "Hello, $name!"
}
println(obj.greet())
medium
A. Runtime error
B. Hello, name!
C. Compilation error
D. Hello, Alice!

Solution

  1. Step 1: Analyze the anonymous object

    The object has a property name with value "Alice" and a function greet() that returns "Hello, $name!".
  2. Step 2: Evaluate the print statement

    Calling obj.greet() returns "Hello, Alice!" which is printed.
  3. Final Answer:

    Hello, Alice! -> Option D
  4. Quick Check:

    obj.greet() = "Hello, Alice!" [OK]
Hint: Object properties accessed inside functions print correctly [OK]
Common Mistakes:
  • Expecting variable name printed instead of value
  • Thinking anonymous objects cause errors
  • Confusing string interpolation syntax
4. Identify the error in this Kotlin code using an object expression:
val obj = object {
    val x = 5
    fun printX() {
        println(y)
    }
}
medium
A. Property 'y' is not defined in the object
B. Missing parentheses after 'object'
C. Function printX() should return a value
D. Cannot use println inside object expressions

Solution

  1. Step 1: Check properties and functions inside the object

    The object defines property x but tries to print y which is not defined.
  2. Step 2: Understand the error cause

    Accessing undefined property y causes a compilation error.
  3. Final Answer:

    Property 'y' is not defined in the object -> Option A
  4. Quick Check:

    Undefined property access = error [OK]
Hint: Check all properties used inside object functions exist [OK]
Common Mistakes:
  • Assuming missing parentheses after 'object' cause error
  • Thinking functions must return a value
  • Believing println is disallowed inside objects
5. How can you use an object expression to create a one-time comparator for sorting a list of strings by length in Kotlin?
hard
A. list.sortedWith(object : Comparator<String> { override fun compare(a: String, b: String) = a.length - b.length })
B. list.sortedWith(object Comparator<String> { fun compare(a: String, b: String) = a.length - b.length })
C. list.sortedWith(object : Comparator<String> { fun compare(a: String, b: String) = a.length - b.length })
D. list.sortedWith(object Comparator<String> { override fun compare(a: String, b: String) = a.length - b.length })

Solution

  1. Step 1: Understand object expression with interface implementation

    To create a comparator, use object : Comparator<String> and override compare method.
  2. Step 2: Check syntax correctness

    list.sortedWith(object : Comparator<String> { override fun compare(a: String, b: String) = a.length - b.length }) correctly uses override fun compare. Options B and D miss the colon before interface or override keyword. list.sortedWith(object : Comparator<String> { fun compare(a: String, b: String) = a.length - b.length }) misses override keyword.
  3. Final Answer:

    list.sortedWith(object : Comparator<String> { override fun compare(a: String, b: String) = a.length - b.length }) -> Option A
  4. Quick Check:

    Correct syntax = object : Interface { override fun method() } [OK]
Hint: Use 'object : Interface { override fun method() }' for anonymous implementations [OK]
Common Mistakes:
  • Omitting colon before interface name
  • Missing override keyword on method
  • Using 'object Interface' instead of 'object : Interface'
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