What if you could create objects with all their data ready, without writing extra setup code every time?
Why Primary constructor and init blocks in Kotlin? - Purpose & Use Cases
Imagine you want to create a class to represent a person. You write code to set the name and age manually inside the class body, repeating the same steps every time you create a new person.
This manual way is slow and easy to mess up. You might forget to set a value or write extra code that makes your class messy and hard to read.
Primary constructors and init blocks let you set up your class neatly and quickly. You can pass values right when you create an object, and the init block helps run extra setup code automatically.
class Person { var name: String = "" var age: Int = 0 fun setup(name: String, age: Int) { this.name = name this.age = age } }
class Person(val name: String, val age: Int) { init { println("Person created: $name, $age years old") } }
You can create clear, concise classes that automatically handle setup, making your code easier to write and understand.
When building an app, you can quickly create user profiles by passing their info directly to the class, and the init block can check if the data is valid right away.
Primary constructors let you pass data when creating objects.
Init blocks run extra setup code automatically after the constructor.
This approach keeps your classes clean and your code simple.
Practice
init block in a Kotlin class with a primary constructor?Solution
Step 1: Understand the role of primary constructor
The primary constructor initializes the properties of the class when an object is created.Step 2: Identify the purpose of the init block
The init block runs immediately after the primary constructor to execute extra setup code or validations.Final Answer:
To run additional code right after the primary constructor initializes properties -> Option BQuick Check:
Init block = extra setup after constructor [OK]
- Confusing init block with secondary constructor
- Thinking init block declares constants
- Assuming init block overrides superclass methods
name and age in Kotlin?Solution
Step 1: Recall Kotlin primary constructor syntax
Primary constructor parameters are declared in parentheses after the class name, separated by commas, with types after colons.Step 2: Check each option
class Person(name: String, age: Int) { } uses correct syntax: parentheses, commas, colons for types. Options A, B, and D have syntax errors.Final Answer:
class Person(name: String, age: Int) { } -> Option AQuick Check:
Primary constructor = class Name(params) [OK]
- Using semicolons instead of commas
- Omitting colons before types
- Confusing primary with secondary constructor syntax
class User(val name: String) {
init {
println("Welcome, $name!")
}
}
fun main() {
val user = User("Anna")
}Solution
Step 1: Understand object creation and init block
When creating User("Anna"), the primary constructor sets name to "Anna" and then the init block runs.Step 2: Analyze the init block output
The init block prints "Welcome, $name!" where $name is replaced by "Anna".Final Answer:
Welcome, Anna! -> Option DQuick Check:
Init block prints welcome message with name [OK]
- Expecting no output because println is inside class
- Confusing variable interpolation syntax
- Thinking init block runs only on demand
class Product(val id: Int) {
init {
println("Product ID: $productId")
}
}Solution
Step 1: Check variable usage in init block
The init block tries to printproductId, but the class has onlyiddeclared.Step 2: Confirm variable declaration
SinceproductIdis not declared anywhere, this causes a compilation error.Final Answer:
VariableproductIdis not declared -> Option CQuick Check:
Use declared property names in init block [OK]
- Assuming init block can't use println
- Thinking primary constructor must be empty
- Believing secondary constructor is mandatory
Employee with a primary constructor that takes name and salary. You also want to print a welcome message and calculate a 10% bonus right after object creation. Which is the best way to do this?Solution
Step 1: Understand primary constructor role
Primary constructor is for receiving parameters and initializing properties simply.Step 2: Use init block for extra setup
Init block runs after constructor to print messages and calculate bonus, keeping code organized.Step 3: Evaluate other options
Secondary constructors are unnecessary here; code can't go inside constructor parentheses; companion object is unrelated.Final Answer:
Use primary constructor for parameters and an init block to print message and calculate bonus -> Option AQuick Check:
Primary constructor + init block = clean setup [OK]
- Trying to put logic inside constructor parentheses
- Using secondary constructors unnecessarily
- Misusing companion object for instance initialization
Ready to prove it?
Pass the test and this pattern moves unknown
