Data classes for value holders in Kotlin - Time & Space Complexity
Let's see how using data classes to hold values affects the time it takes to run code.
We want to know how the program's work grows when we create many data class objects.
Analyze the time complexity of the following code snippet.
data class Point(val x: Int, val y: Int)
fun createPoints(n: Int): List {
val points = mutableListOf()
for (i in 0 until n) {
points.add(Point(i, i * 2))
}
return points
}
This code creates a list of n Point objects, each holding two numbers.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Creating and adding a Point object inside a loop.
- How many times: Exactly
ntimes, once per loop iteration.
Each time we increase n, we do more work creating and storing points.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 creations and additions |
| 100 | 100 creations and additions |
| 1000 | 1000 creations and additions |
Pattern observation: The work grows directly with n. Double the input, double the work.
Time Complexity: O(n)
This means the time to create points grows in a straight line with the number of points.
[X] Wrong: "Creating data class objects is instant and doesn't add to time."
[OK] Correct: Each object creation takes time, so more objects mean more total time.
Understanding how creating many simple objects affects time helps you explain performance clearly in interviews.
"What if we changed the loop to create points only for even numbers? How would the time complexity change?"
Practice
data class in Kotlin?Solution
Step 1: Understand the role of data classes
Data classes are designed to hold data and automatically provide useful functions liketoString(),equals(), andhashCode().Step 2: Compare options with data class purpose
Options A, B, and D describe unrelated tasks. Only To hold data with automatically generated functions liketoString()andequals()matches the purpose of data classes.Final Answer:
To hold data with automatically generated functions like toString() and equals() -> Option CQuick Check:
Data class purpose = hold data simply [OK]
- Confusing data classes with UI or database classes
- Thinking data classes perform calculations
- Ignoring the automatic function generation feature
Person with properties name (String) and age (Int)?Solution
Step 1: Recall data class syntax
In Kotlin, a data class is declared with the keyworddata classfollowed by the class name and primary constructor with properties.Step 2: Check each option
class Person(val name: String, val age: Int) misses thedatakeyword. data Person(val name: String, val age: Int) usesdatawithoutclass. class data Person(name: String, age: Int) incorrectly orders keywords. Only data class Person(val name: String, val age: Int) is correct.Final Answer:
data class Person(val name: String, val age: Int) -> Option AQuick Check:
Correct syntax = data class + name + properties [OK]
- Omitting the 'data' keyword
- Swapping 'data' and 'class' keywords
- Not using 'val' or 'var' for properties
data class Point(val x: Int, val y: Int)
fun main() {
val p1 = Point(3, 4)
val p2 = Point(3, 4)
println(p1 == p2)
println(p1)
}Solution
Step 1: Understand equality in data classes
Data classes automatically generateequals()that compares property values, sop1 == p2istruebecause both have same x and y.Step 2: Understand toString() output
Data classes generatetoString()that prints property names and values likePoint(x=3, y=4).Final Answer:
true Point(x=3, y=4) -> Option BQuick Check:
Data class equality and toString() = true and Point(x=3, y=4) [OK]
- Assuming == compares references, not values
- Expecting default toString() without property names
- Confusing output format of toString()
data class User(name: String, age: Int)
Solution
Step 1: Check primary constructor properties
In data classes, properties in the primary constructor must be marked withvalorvarto become class properties.Step 2: Analyze the given code
The code lacksvalorvarbeforenameandage, so they are just parameters, not properties.Final Answer:
Missing val or var before properties in the constructor -> Option DQuick Check:
Constructor properties need val/var [OK]
- Forgetting val/var in data class constructor
- Thinking data keyword position is wrong
- Assuming class names can be lowercase
Book with properties title (String), author (String), and year (Int). You also want to create a copy of a Book instance but change only the year. Which Kotlin feature helps you do this easily?Solution
Step 1: Recall data class features
Data classes automatically generate acopy()function that creates a new instance copying all properties, allowing selective changes.Step 2: Match the feature to the problem
Thecopy()function automatically generated for data classes describes thecopy()function which fits the need to copy and change onlyyear. Other options are less efficient or unrelated.Final Answer:
The copy() function automatically generated for data classes -> Option AQuick Check:
Use copy() to clone and modify data class instances [OK]
- Not knowing about the copy() function
- Trying to manually copy all properties
- Confusing inheritance with copying
Ready to prove it?
Pass the test and this pattern moves unknown
