What Are Constructors in Kotlin?
In Kotlin, a constructor is a special function used to create and initialize objects. It assigns values to properties via parameters or defaults. A class can have multiple constructors for flexible instantiation.
Types of Constructors in Kotlin
Kotlin has two types: primary constructor (in class header) and secondary constructors (in class body with constructor keyword).
How Kotlin Constructors Differ from Java
Kotlin declares and initializes properties directly in the primary constructor, reducing boilerplate compared to Java's separate field declarations and assignments.
- Java: Fields declared separately, assigned in constructor body.
- Kotlin: Properties declared and initialized in one step.
Java Example:
public class Person {
private String name;
private int age;
public Person(String name, int age) {
this.name = name;
this.age = age;
}
}
Kotlin Equivalent:
class Person(val name: String, var age: Int)
Primary Constructor
Defined in the class header; concise for declaring properties. Cannot contain code directly — use init blocks for initialization logic.
class Person(val name: String, val age: Int) {
init {
println("Person created: $name, age $age")
}
}
Init Blocks
init blocks execute immediately after the primary constructor, in the order they appear. Used for validation, logging, or additional setup. Multiple init blocks are allowed and run sequentially.
class Demo(val value: String) {
init { println("First init") }
init { println("Second init") }
}
// Output: First init → Second init
Secondary Constructors
Defined inside the class body with constructor. Must delegate to the primary constructor (if present) using this(...). init blocks run before secondary constructor body code.
class Book(val title: String, val pages: Int = 0) {
constructor(title: String) : this(title) {
println("Secondary constructor called")
}
init {
println("Init block: $title")
}
}
// init runs first, then secondary body
Execution Order
- Primary constructor parameters are used to initialize properties.
- All
initblocks execute in order. - Secondary constructor body (if used) executes last.
When Constructors Cannot Be Customized
In framework classes (e.g., Android Activity/Fragment), constructors are restricted. Use alternatives:
- Factory methods
- Builder pattern
- Lifecycle callbacks (e.g.,
onCreate())
Kotlin Constructor Summary
- Primary constructor — concise property declaration in header; no code body.
initblocks — run after primary, before secondary; multiple allowed in order.- Secondary constructors — delegate to primary with
this(); body runs after allinitblocks. - Execution flow — primary → init blocks → secondary body.