Kotlin has a fresh take on constructors. You get a primary constructor built into the class header, plus an init block for setup logic. And if you need more flexibility, secondary constructors have your back.
Primary constructor
The primary constructor is part of the class declaration itself. It lives right after the class name.
class User(val username: String, val email: String)
fun main() {
val user = User("alice42", "alice@example.com")
println("Welcome, ${user.username}!")
}
When you write class User(val username: String, val email: String), Kotlin automatically creates both the constructor and the properties. One line, two jobs.
The init block
Need to run some code when an object is created? Use the init block. It executes right after the primary constructor.
class Student(val name: String, val id: Int) {
init {
println("Student $name (ID: $id) created")
}
}
fun main() {
val s1 = Student("Bob", 101)
val s2 = Student("Diana", 102)
}
You can have multiple init blocks — they run in the order they appear in the class body.
Secondary constructors
Sometimes you need multiple ways to create an object. That's what secondary constructors are for. Use the constructor keyword.
class Rectangle(val width: Int, val height: Int) {
constructor(side: Int) : this(side, side) {
println("Created a square: $side x $side")
}
}
fun main() {
val rect = Rectangle(4, 5)
val square = Rectangle(6)
}
Secondary constructors must delegate to the primary constructor using this(). In this example, passing one value creates a square.