Object expressions (anonymous objects) in Kotlin - Time & Space Complexity
Let's see how the time cost changes when we use object expressions, also called anonymous objects, in Kotlin.
We want to know how the program's work grows as we create more of these objects.
Analyze the time complexity of the following code snippet.
fun createObjects(n: Int) {
repeat(n) {
val obj = object {
val x = it
fun greet() = "Hello $x"
}
println(obj.greet())
}
}
This code creates n anonymous objects, each with a property and a function, then prints a greeting.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Creating an anonymous object and calling its function inside a loop.
- How many times: Exactly
ntimes, once per loop iteration.
Each time we increase n, we create one more object and call its function once.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 object creations and 10 function calls |
| 100 | 100 object creations and 100 function calls |
| 1000 | 1000 object creations and 1000 function calls |
Pattern observation: The work grows evenly with n. Double n, double the work.
Time Complexity: O(n)
This means the time needed grows in a straight line with the number of objects created.
[X] Wrong: "Creating anonymous objects inside a loop is free or constant time because they are anonymous."
[OK] Correct: Each object creation takes time, and doing it n times adds up linearly.
Understanding how object creation inside loops affects time helps you write clear and efficient Kotlin code, a skill valued in many coding challenges.
What if we moved the anonymous object creation outside the loop and reused it? How would the time complexity change?
Practice
object expression in Kotlin?Solution
Step 1: Understand object expressions
Object expressions create unnamed objects on the spot with properties and functions.Step 2: Differentiate from other options
Named classes, functions, and variables are different concepts and do not create anonymous objects.Final Answer:
A way to create an anonymous object with properties and functions -> Option BQuick Check:
Object expression = anonymous object [OK]
- Confusing object expressions with named classes
- Thinking object expressions are functions
- Assuming object expressions are variables
Solution
Step 1: Recall Kotlin object expression syntax
The correct syntax usesobject { ... }without parentheses.Step 2: Check each option
val obj = object { val x = 10 } matches the correct syntax. val obj = class { val x = 10 } usesclasswhich is invalid here. val obj = fun() { val x = 10 } usesfun()which is a function, not an object. val obj = object() { val x = 10 } incorrectly adds parentheses afterobject.Final Answer:
val obj = object { val x = 10 } -> Option CQuick Check:
Correct syntax = object { ... } [OK]
- Adding parentheses after 'object'
- Using 'class' instead of 'object'
- Confusing functions with object expressions
val obj = object {
val name = "Alice"
fun greet() = "Hello, $name!"
}
println(obj.greet())Solution
Step 1: Analyze the anonymous object
The object has a propertynamewith value "Alice" and a functiongreet()that returns "Hello, $name!".Step 2: Evaluate the print statement
Callingobj.greet()returns "Hello, Alice!" which is printed.Final Answer:
Hello, Alice! -> Option DQuick Check:
obj.greet() = "Hello, Alice!" [OK]
- Expecting variable name printed instead of value
- Thinking anonymous objects cause errors
- Confusing string interpolation syntax
val obj = object {
val x = 5
fun printX() {
println(y)
}
}Solution
Step 1: Check properties and functions inside the object
The object defines propertyxbut tries to printywhich is not defined.Step 2: Understand the error cause
Accessing undefined propertyycauses a compilation error.Final Answer:
Property 'y' is not defined in the object -> Option AQuick Check:
Undefined property access = error [OK]
- Assuming missing parentheses after 'object' cause error
- Thinking functions must return a value
- Believing println is disallowed inside objects
Solution
Step 1: Understand object expression with interface implementation
To create a comparator, useobject : Comparator<String>and overridecomparemethod.Step 2: Check syntax correctness
list.sortedWith(object : Comparator<String> { override fun compare(a: String, b: String) = a.length - b.length }) correctly usesoverride 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.Final Answer:
list.sortedWith(object : Comparator<String> { override fun compare(a: String, b: String) = a.length - b.length }) -> Option AQuick Check:
Correct syntax = object : Interface { override fun method() } [OK]
- Omitting colon before interface name
- Missing override keyword on method
- Using 'object Interface' instead of 'object : Interface'
Ready to prove it?
Pass the test and this pattern moves unknown
