Explain it simply
Explain it simply
A constructor is the moment an object is born. When you write Person("John", 35) you hand over the information the new object needs before anybody can use it, much like filling in a form before it is filed. Kotlin lets you write the form fields straight after the class name, which is why many Kotlin classes fit on a single line.
The parameters in that header are only the paperwork. Putting val or var in front of one also turns it into a property that stays on the object. Without val or var, the value is visible while the object is being built and then gone.
Problem → Why → Solution
The problem: half-built objects
Without constructor parameters, creating an object and filling it in become two separate steps. You call Person() and then set the fields one by one. Forget one and you hold an object with a blank name, nothing stops age = -5, and every place that creates a Person repeats the same setup lines.
class Person {
var firstName: String = ""
var age: Int = 0
}
fun main() {
val p = Person()
p.age = -5 // nothing stops this
println("'${p.firstName}' is ${p.age}") // '' is -5
}Why is optional setup not enough?
An object that can exist half-built forces every reader of the object to check whether it is valid. A constructor makes validity a precondition of existence: if Person("", -5) is rejected inside init, no Person with a blank name can ever exist. Callers have fewer checks to make, and the rules for what a valid Person is sit next to the class instead of being repeated everywhere.
Core concept: the header, init blocks and the order
The primary constructor lives in the class header: class Person(val firstName: String, var age: Int). A parameter with val or var is also a property. A parameter with neither is a plain parameter: you can use it in property initializers and init blocks, and after that it is gone. The constructor keyword is only needed when there is a modifier or annotation, as in class Port private constructor(...).
A header cannot hold code, so validation and setup go into init blocks. Property initializers and init blocks run top to bottom in the order they appear in the class body, and you may write more than one init block. Using a property inside an init block before its declaration gives an error such as "variable 'area' must be initialized". Rejecting bad input with require(condition) { message } throws IllegalArgumentException and no object is created.
Default and named arguments replace the piles of overloads you may know from Java. With city: String = "Yangon", both Person("Aye", 30) and Person("Aye", 30, "Mandalay") work. Named arguments can be written in any order, as in Person(city = "Mandalay", age = 41, firstName = "Kyaw"), and they protect you from passing two Strings in the wrong order.
Secondary constructors are written with the constructor keyword, and when a primary constructor exists they must delegate to it with this(...), directly or through another secondary constructor. Otherwise you get "primary constructor call expected". The delegate runs first, including the primary constructor's init blocks, and only then does the secondary constructor's own body run. Prefer default arguments when they are enough, and keep secondary constructors for genuinely different input shapes, such as building a user from an email address.
| Parameter style | Becomes a property? | Visible where |
|---|---|---|
| name: String | No | Header, init blocks, property initializers |
| val name: String | Yes, read-only | Everywhere the class is visible |
| var name: String | Yes, read-write | Everywhere, and writable |
| private val name: String | Yes, private | Inside the class only |
- Caller passes arguments to the header
- Initializers and init blocks run in order
- A secondary body runs after its delegate
- The finished object is handed back
If a require inside init fails, no object comes out, so every object that exists has passed the checks.
General pattern
class ClassName(
val readOnly: Type,
var editable: Type,
plainParam: Type,
val withDefault: Type = defaultValue,
) {
init { /* validate, e.g. require(condition) { "message" } */ }
constructor(other: Type) : this(arg1, arg2, arg3)
}Each header parameter can be val, var or neither, and may carry a default value. The init block is for validation. constructor(...) : this(...) is a second way in that hands the work back to the primary constructor.
Example: a Person with two properties declared in the header
The whole class is one line. The header lists the data every Person needs, and val and var decide which parts may change later. main supplies both values in order and reads the two properties back inside a template. Then rewrite the call as Person(firstName = "John", age = 35); the result is identical.
class Person(val firstName: String, var age: Int)
fun main() {
val person = Person("John", 35)
println("${person.firstName} is ${person.age} years old.")
}Code breakdown
- Header and class in one line
class Person(val firstName: String, var age: Int)The primary constructor sits right beside the class name. No body is needed, so there are no braces. The header tells the compiler that building a Person requires both a firstName and an age.
- A read-only property
val firstName: StringBecause of val, firstName is a read-only property with only a getter. person.firstName = "x" would not compile, which declares that a name never changes after construction.
- A read-write property
var age: Intvar gives age both a getter and a setter. After construction it can still change, for example person.age += 1 on every birthday. Use var only for data that really changes.
- Call with positional arguments
Person("John", 35)Arguments pair up with header parameters in order: "John" goes to firstName and 35 goes to age. If someone reorders the parameters, positional calls like this can break without any message, which is why named arguments are safer.
- Read both properties
println("${person.firstName} is ${person.age} years old.")The template reads both properties through their getters. Without val or var in the header, person.firstName would be an "unresolved reference 'firstName'" error.
John is 35 years old.- Person("John", 35) is called
- Arguments are bound to the header parameters
- Property initializers and init blocks run top to bottom
- Did every check in init pass?
All checks pass
the finished Person is returned
A require fails
IllegalArgumentException is thrown and no Person exists
init blocks, defaults and named arguments
The class below has two init blocks with a property initializer between them. The order is top to bottom: the first init prints and rejects bad input, then label is computed, and only then can the second init see label. Move the second init above label and it no longer compiles, because label would not exist yet. main shows three calls: one using the default city, one with named arguments in any order, and one where require rejects a blank name.
class Person(val firstName: String, val age: Int, val city: String = "Yangon") {
init {
println("init A: $firstName")
require(firstName.isNotBlank()) { "firstName must not be blank" }
require(age in 0..150) { "age out of range: $age" }
}
val label: String = "$firstName ($age) from $city"
init {
println("init B: $label")
}
}
fun main() {
val a = Person("Aye", 30)
println(a.label)
val b = Person(city = "Mandalay", age = 41, firstName = "Kyaw")
println(b.label)
try {
Person(" ", 20)
} catch (e: IllegalArgumentException) {
println("rejected: " + e.message)
}
}Secondary constructors and delegation
The User class has three constructors. The primary one needs every value. The first secondary fixes active to true and prints a message from its own body. The second secondary takes only an email address and uses the part before @ as the name. Watch the order: User("zaw@example.com") delegates twice, so it also triggers the first secondary's message. And whichever constructor you enter through, init blocks and property initializers run exactly once, as part of the primary constructor.
class User(val name: String, val email: String, val active: Boolean) {
constructor(name: String, email: String) : this(name, email, true) {
println("secondary ran for $name")
}
constructor(email: String) : this(email.substringBefore("@"), email)
}
fun main() {
val a = User("Aye", "aye@example.com", false)
val b = User("Kyaw", "kyaw@example.com")
val c = User("zaw@example.com")
println("${a.name} ${a.active}")
println("${b.name} ${b.active}")
println("${c.name} ${c.active}")
}Private constructors and factory functions
Sometimes the right answer to bad input is not an exception but the result "cannot be built". A constructor can only return an object, never null, so you make the constructor private and expose a factory function in the companion object. Port.parse("8080") returns a Port, while "99999" and "web" return null, and the caller handles the null. With this pattern an invalid Port can never exist.
class Port private constructor(val number: Int) {
companion object {
fun parse(text: String): Port? {
val n = text.toIntOrNull() ?: return null
return if (n in 1..65535) Port(n) else null
}
}
}
fun main() {
println(Port.parse("8080")?.number)
println(Port.parse("99999"))
println(Port.parse("web"))
}In real projects
Where this shows up in real projects
In real projects the constructor is the main door for dependencies. Writing class OrderService(private val repository: OrderRepository) makes it explicit that whoever builds the service must supply a repository, and a test can pass a fake in place of the real one. Frameworks such as Spring and Hilt read constructor parameters to know what to supply on your behalf.
Settings and request objects can be declared with one constructor full of default arguments, which removes the long builder classes Java needs. You write only what you want to change, as in HttpClientConfig(timeoutSeconds = 5). Data that arrives from outside the program, a form, JSON or the command line, is usually checked once by a factory such as Port.parse, and the rest of the code then handles only valid objects.
Common mistakes
Common mistakes
1. Forgetting val or var in the header
In class Person(firstName: String, var age: Int), firstName is not a property, so person.firstName fails with "unresolved reference 'firstName'". Add val or var when outsiders should read it; leaving both off is correct when only the constructor needs it.
2. Passing same-typed arguments in the wrong order
User("aye@example.com", "Aye") compiles even though name and email are swapped, because both are Strings, and the data is silently wrong. When a call has two or more parameters of the same type, use named arguments such as User(name = ..., email = ...).
3. Using a property in init before it is declared
Writing init { println(area) } above val area = width * 2 gives "variable 'area' must be initialized", because init blocks and initializers run in the order they appear. Move the init block below the properties it uses.
4. A secondary constructor that does not delegate
In a class with a primary constructor, constructor(name: String, email: String) { ... } without a this(...) call fails with "primary constructor call expected". Every secondary constructor must reach the primary one through this(...).
Best practices
Best practices
- Validate in init with require so an invalid object can never exist.
- Prefer default arguments over several secondary constructors.
- Use named arguments at the call site when two parameters share a type or the call has more than three arguments.
Mini challenge
Mini challenge: a Rectangle class
Write a Rectangle class that refuses invalid sizes and offers a second constructor for squares.
- Declare width and height as read-only properties in the primary constructor
- In an init block, reject non-positive sides with require; the message looks like sides must be positive, got 0x2
- Add a secondary constructor so that Rectangle(side) builds a square
- Expose area and perimeter as properties with getters, and in main use a named-argument call and catch the rejection
class Rectangle(/* TODO: width and height as read-only properties */) {
// TODO: init block: require both sides to be positive
// TODO: constructor(side: Int) that delegates to the primary one
// TODO: area and perimeter as properties with getters
}
fun main() {
// TODO: build Rectangle(width = 4, height = 3) and Rectangle(5)
// TODO: print "area perimeter" for each, for example "12 14"
// TODO: catch the exception for Rectangle(0, 2) and print its message
}Expected: The program prints these three lines: 12 14 25 20 sides must be positive, got 0x2
Show hint
Write the secondary constructor as constructor(side: Int) : this(side, side). The message uses a template such as "sides must be positive, got ${width}x$height". Catch the failure with catch (e: IllegalArgumentException) and print e.message.
Show solution
class Rectangle(val width: Int, val height: Int) {
init {
require(width > 0 && height > 0) {
"sides must be positive, got ${width}x$height"
}
}
constructor(side: Int) : this(side, side)
val area: Int
get() = width * height
val perimeter: Int
get() = 2 * (width + height)
}
fun main() {
val r = Rectangle(width = 4, height = 3)
val s = Rectangle(5)
println("${r.area} ${r.perimeter}")
println("${s.area} ${s.perimeter}")
try {
Rectangle(0, 2)
} catch (e: IllegalArgumentException) {
println(e.message)
}
}Quick quiz 1 / 3
Quick quiz 2 / 3
Quick quiz 3 / 3
What to remember
- The primary constructor lives in the class header; a val or var parameter is also a property, and a plain parameter is visible only during construction.
- Property initializers and init blocks run top to bottom in the order written, and a require inside init refuses to build an invalid object.
- Default and named arguments replace piles of overloads and guard against swapping same-typed parameters.
- A secondary constructor must delegate with this(...); when rejection should mean null, use a private constructor and a companion factory.
Kotlin language guide — Kotlin