Kotlin Constructors
A constructor prepares a new object: it receives the initial values and makes sure the object starts in a valid state. Kotlin has a compact primary constructor in the class header, init blocks for setup code, and optional secondary constructors.
The primary constructor
class Pet(val name: String, val species: String, var age: Int)
fun main() {
val pet = Pet("Bella", "cat", 3)
pet.age++
println("${pet.name} the ${pet.species} is ${pet.age}")
}Bella the cat is 4
| Parameter form | Becomes a property? |
|---|---|
val name: String |
yes, read-only |
var age: Int |
yes, mutable |
name: String (no val/var) |
no — only usable in initializers and init |
Default values and named arguments
Constructor parameters can have defaults and be passed by name, exactly like function parameters:
class Pizza(val size: String = "medium", val cheese: Boolean = true, val toppings: List<String> = emptyList())
fun main() {
val p1 = Pizza()
val p2 = Pizza("large", toppings = listOf("olives", "basil"))
val p3 = Pizza(cheese = false)
println("${p1.size}, cheese=${p1.cheese}, ${p1.toppings}")
println("${p2.size}, cheese=${p2.cheese}, ${p2.toppings}")
println("${p3.size}, cheese=${p3.cheese}, ${p3.toppings}")
}medium, cheese=true, []
large, cheese=true, [olives, basil]
medium, cheese=false, []
init blocks
The primary constructor can't contain statements, so setup logic goes into init blocks. They run in order, as part of construction. require is a neat way to validate arguments — it throws IllegalArgumentException if the condition is false:
class Temperature(val celsius: Double) {
val fahrenheit: Double
init {
require(celsius >= -273.15) { "Below absolute zero: $celsius" }
fahrenheit = celsius * 9 / 5 + 32
println("Created $celsius °C")
}
}
fun main() {
val t = Temperature(25.0)
println(t.fahrenheit)
try {
Temperature(-300.0)
} catch (e: IllegalArgumentException) {
println("Error: ${e.message}")
}
}Created 25.0 °C
77.0
Error: Below absolute zero: -300.0
Properties computed from parameters
Plain constructor parameters (without val/var) can initialise other properties:
class Rectangle(width: Int, height: Int) {
val area = width * height
val isSquare = width == height
}
fun main() {
val r = Rectangle(4, 5)
println("area=${r.area}, square=${r.isSquare}")
}area=20, square=false
Here width and height aren't stored — r.width would be a compile error.
Secondary constructors
A secondary constructor is declared with constructor inside the class. If there's a primary constructor, each secondary one must delegate to it with : this(...):
class Color(val red: Int, val green: Int, val blue: Int) {
constructor(gray: Int) : this(gray, gray, gray)
constructor(hex: String) : this(
hex.substring(1, 3).toInt(16),
hex.substring(3, 5).toInt(16),
hex.substring(5, 7).toInt(16)
)
fun describe() = "rgb($red, $green, $blue)"
}
fun main() {
println(Color(255, 128, 0).describe())
println(Color(200).describe())
println(Color("#7F52FF").describe())
}rgb(255, 128, 0)
rgb(200, 200, 200)
rgb(127, 82, 255)
Tip: Default arguments make most secondary constructors unnecessary. Reach for
constructoronly when the alternative inputs are genuinely different (like a hex string vs. three numbers), or for Java interop.
Order of initialisation
When an object is created, Kotlin runs property initialisers and init blocks in the order they appear in the class body, then the body of the secondary constructor (if one was called).
Test yourself
Where do you put validation code that should run when an object is created?
- In the class header
- In an init block
- In main
- In a companion object
In class A(x: Int), is x a property you can read from outside?
- Yes
- No, it is only a constructor parameter
- Only if it is an Int
- Only inside main
What must a secondary constructor do when the class has a primary constructor?
- Nothing special
- Delegate to it with
: this(...) - Call super()
- Be private