Class declaration syntax in Kotlin - Time & Space Complexity
Let's see how the time it takes to create a class grows as we add more properties or methods.
We want to know how the work changes when the class size changes.
Analyze the time complexity of the following code snippet.
class Person(val name: String, val age: Int) {
fun greet() {
println("Hello, my name is $name.")
}
}
fun main() {
val person = Person("Alice", 30)
person.greet()
}
This code defines a simple class with two properties and one method, then creates an object and calls the method.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Creating an instance of the class and calling its method.
- How many times: Once in this example, no loops or repeated calls.
When we add more properties or methods, creating the class and its objects takes more steps.
| Input Size (number of properties/methods) | Approx. Operations |
|---|---|
| 1 | Few steps to set up and call |
| 5 | More steps to initialize and manage |
| 10 | Even more steps, roughly growing with number of members |
Pattern observation: The work grows roughly in a straight line as you add more parts to the class.
Time Complexity: O(n)
This means the time to create and use the class grows linearly with the number of properties and methods it has.
[X] Wrong: "Creating a class is always instant and does not depend on its size."
[OK] Correct: Even though creating an instance looks simple, the computer does more work as the class has more parts to set up.
Understanding how class size affects work helps you explain your code design choices clearly and confidently.
"What if we added a loop inside the class method that runs over a list of size n? How would the time complexity change?"
Practice
Car in Kotlin?Solution
Step 1: Understand Kotlin class declaration syntax
Kotlin uses the keywordclassfollowed by the class name and curly braces to declare a class.Step 2: Check each option
class Car { } usesclass Car { }, which is correct. Options B and C use keywords from other languages. class Car() misses curly braces which are required for an empty class body.Final Answer:
class Car { } -> Option BQuick Check:
Kotlin class declaration = class ClassName { } [OK]
- Using 'def' or 'function' instead of 'class'
- Omitting curly braces for class body
- Adding parentheses without constructor parameters
Person with a primary constructor having a name parameter of type String?Solution
Step 1: Recall Kotlin primary constructor syntax
In Kotlin, the primary constructor is declared in parentheses after the class name with parameter types specified using a colon.Step 2: Evaluate options
class Person(name: String) { } correctly declaresclass Person(name: String) { }. class Person { val name: String } declares a property inside the class but no constructor. class Person(name String) { } misses colon between parameter and type. class Person(name: String) misses curly braces for class body.Final Answer:
class Person(name: String) { } -> Option AQuick Check:
Primary constructor syntax = class Name(params) { } [OK]
- Omitting colon between parameter and type
- Forgetting curly braces for class body
- Declaring properties without constructor parameters
class Animal(val name: String) {
fun speak() = "Hello, I am $name"
}
fun main() {
val dog = Animal("Buddy")
println(dog.speak())
}Solution
Step 1: Understand class and function behavior
The classAnimalhas a propertynameand a functionspeak()that returns a greeting using thename.Step 2: Trace the code execution
Inmain, anAnimalobject nameddogis created withname = "Buddy". Callingdog.speak()returns "Hello, I am Buddy" which is printed.Final Answer:
Hello, I am Buddy -> Option DQuick Check:
String interpolation with property = Hello, I am Buddy [OK]
- Confusing property name with literal string
- Expecting class name instead of property value
- Assuming syntax error due to string interpolation
class Book(title: String) {
fun printTitle() {
println(title)
}
}Solution
Step 1: Analyze constructor and property declaration
The primary constructor parametertitleis not declared withvalorvar, so it is not a property of the class.Step 2: Understand Kotlin property initialization
Sincetitleis only a parameter, it cannot be accessed by name inside the class methods likeprintTitle(), causing a compilation error. Useval title: Stringin the constructor to make it a property.Final Answer:
Primary constructor parameter should be declared with val or var -> Option AQuick Check:
Constructor params need val/var for properties [OK]
- Thinking function must return a value
- Assuming properties must be nullable
- Believing class cannot have functions
Student that stores name and grade with default grade 0. How do you declare it so that grade is optional when creating an object?Solution
Step 1: Understand default parameter values in constructors
Kotlin allows default values for constructor parameters, making them optional when creating objects.Step 2: Check options for default grade
class Student(val name: String, val grade: Int = 0) { } declaresgradewith default 0 in constructor, so it can be omitted. class Student(val name: String, val grade: Int) { init { grade = 0 } } tries to assign in init block butgradeis val and cannot be reassigned. class Student(val name: String) { var grade = 0 } declares grade as property but not in constructor, so not optional parameter. class Student(val name: String, grade: Int = 0) { val grade = 0 } declaresgradewithout val/var in constructor, so it's not a property, and then declares property separately, which is confusing.Final Answer:
class Student(val name: String, val grade: Int = 0) { } -> Option CQuick Check:
Default constructor params = val param: Type = value [OK]
- Trying to assign val properties inside init block
- Not using val/var for constructor parameters
- Declaring properties outside constructor without defaults
Ready to prove it?
Pass the test and this pattern moves unknown
