Kotlin Constructors
Constructors let you supply initial values to an object's properties at the moment it is created.
The Primary Constructor
Kotlin's primary constructor is part of the class header itself, right after the class name. Parameters declared there with val or var automatically become properties of the class, eliminating the need to manually assign fields inside a constructor body.
Primary Constructor Basics
class Employee(val name: String, var salary: Double)
fun main() {
val emp = Employee("Diego", 55000.0)
println("${emp.name} earns ${emp.salary}")
emp.salary += 5000.0
println("New salary: ${emp.salary}")
}The init Block
If you need to run logic during initialization - like validation or computing a derived value - use an init block. Init blocks execute in the order they appear, interleaved with property initializers, right after the primary constructor runs.
Using init for Validation
class Employee(val name: String, var salary: Double) {
init {
require(salary >= 0) { "Salary cannot be negative" }
println("Created employee record for $name")
}
}
fun main() {
val emp = Employee("Priya", 62000.0)
}Secondary Constructors
A class can also declare one or more secondary constructors using the constructor keyword. Secondary constructors must delegate to the primary constructor (directly or indirectly) using the this(...) syntax, which keeps a single source of truth for initialization.
Secondary Constructor Delegation
class Employee(val name: String, var salary: Double) {
constructor(name: String) : this(name, 40000.0)
}
fun main() {
val defaultEmp = Employee("Sam")
println("${defaultEmp.name} starts at ${defaultEmp.salary}")
}- Primary constructor lives in the class header and can hold val/var parameters
- Secondary constructors use the constructor keyword inside the class body
- Every secondary constructor must call the primary constructor via this(...)
- init blocks run as part of the primary constructor's initialization sequence
With constructors in place, you're ready to explore class functions - the behavior that operates on an object's properties.
Exercise: Kotlin Constructors
Where is a Kotlin primary constructor declared?