1. Primary constructor: the “front door” to a class
When we start writing classes, it’s tempting to think: “Well, a constructor is just a way to shove values inside.” But in reality, a constructor is the public entry point to your type, i.e., part of the class API. It’s like the front door to an office: you can make it convenient and clearly labeled, or you can install 12 identical doors with no signs—and then be surprised that employees keep walking into the server room.
In Kotlin, the main way to create an object is the primary constructor, which is written right in the class header. It’s considered the “main creation route,” and the rest of the code is usually built around it. Kotlin documentation states this explicitly: the primary constructor is declared in the header, and parameters can become properties via val/var.
A simple example of a “class as an object-creation function”:
class User(val name: String, var age: Int)
fun main() {
val u = User(name = "Ann", age = 20)
println(u.name) // Ann
u.age += 1
println(u.age) // 21
}
Notice another “nice Kotlin bonus”: when creating an object, you don’t need new—you call the class like a function.
It’s a small thing, but it makes code more compact: fewer “ritual words,” more meaning.
2. Constructor parameter vs property: what becomes state
This is where almost every beginner steps on the same rake. It seems logical: “I wrote class X(a: Int)—so the object has a.” But no: a constructor parameter without val/var is just an input value, like a function parameter. It doesn’t have to become part of the object’s state.
Kotlin can do a neat thing: if a parameter is declared with val or var, it is simultaneously a constructor parameter and an object property. This is one of the key elements of “Kotlin style”—less boilerplate.
Let’s compare two variants.
Variant A: the parameter is a property
class Label(val text: String)
fun main() {
val l = Label("Hi")
println(l.text) // Hi
}
Variant B: the parameter is not a property
class Label(text: String) {
val text: String = text
}
fun main() {
val l = Label("Hi")
println(l.text) // Hi
}
Both variants work, but they mean different things. In variant B, you’re sort of saying: “At creation time I was given text, but what I’ll store is text (my own).” Kotlin documentation explicitly emphasizes that parameters without val/var are not stored as properties and are only available in the class body until you assign them to a property.
So you don’t have to keep this “by feel,” it helps to pin it down like this:
| Header form | Is this an object property? | Can you access it from outside (obj.x)? | Typical meaning |
|---|---|---|---|
|
no | no | an input value “at creation time” |
|
yes (read-only) | yes | part of the state, cannot be changed |
|
yes (mutable) | yes | part of the state, can be changed |
3. Designing Expense: a type that’s pleasant to create
Here’s an important practical idea: a good constructor is one that’s pleasant to look at at the call site. Because the real pain isn’t writing the class—it’s opening the code a month later and figuring out what Expense(1, "Taxi", 900, "transport") means—was it a taxi for 9 USDT or for 900 USDT, and what even is that “1”.
Let’s imagine that in our console expense tracker, one record is an expense: it has an identifier, a title, an amount (in whole units so we don’t suffer with Double), and a category as a string (for now a string: enum will come later).
Let’s start simple:
class Expense(
val id: Int,
val title: String,
val amount: Int,
val category: String
)
fun main() {
val e = Expense(1, "Coffee", 350, "food")
println(e.title) // Coffee
println(e.amount) // 350
}
Already not bad: it’s one object, everything is together, and we no longer glue data “by index” across different lists.
But honestly: the line Expense(1, "Coffee", 350, "food") is only moderately readable. With four parameters it’s still tolerable, but as soon as a fifth shows up, it becomes a guessing game.
This is where the constructor as an API shows up especially clearly: we’re not only choosing types, we’re also designing the readability of the call.
4. Default values: less chaos when creating
At some point you’ll want: “Let the category be optional—if it’s not provided, we’ll consider it "other".” And here you have two paths. One path is to build several creation variants (spoiler: secondary constructors will come later). The second path is default values.
The primary constructor supports default values just like functions do. This is officially described: you can set defaults right in the constructor parameters, and if an argument isn’t passed, the default value is used.
Let’s do this:
class Expense(
val id: Int,
val title: String,
val amount: Int,
val category: String = "other"
)
fun main() {
val a = Expense(1, "Coffee", 350)
val b = Expense(2, "Taxi", 900, "transport")
println(a.category) // other
println(b.category) // transport
}
An important effect: now our class has fewer “creation modes”, and that’s good. The reader’s brain shouldn’t have to remember that “if the category didn’t arrive, you must create the object differently.” The class itself “knows” how to start correctly.
In practice, defaults most often give you two wins. First, they reduce the amount of required data: we keep as required only what the object makes no sense without. Second, they reduce mistakes when creating: fewer places where you must “not forget something.”
5. Named arguments: readability at the call site
Now we’ll do the thing that turns “four parameters is tolerable” into “six parameters is still readable”: named arguments.
The key idea is simple: constructor parameter names are not just “whatever you called them internally.” They are part of the external interface: people will see them in calls, especially if they use named arguments. So a bad parameter name in a constructor is like a bad label on a button in an app.
Look how much clearer it is:
class Expense(
val id: Int,
val title: String,
val amount: Int,
val category: String = "other"
)
fun main() {
val e = Expense(
id = 10,
title = "Lunch",
amount = 550,
category = "food"
)
println(e.title) // Lunch
println(e.amount) // 550
}
Yes, it’s a bit longer. But “length” here works as insurance against mistakes—especially when parameters of the same type repeat. Two String lines in a row are a classic source of “I swapped them and didn’t notice.”
To see how easy it is to make a mistake without named arguments, imagine a class:
class Client(val firstName: String, val lastName: String)
fun main() {
val c = Client("Ivan", "Petrov")
println("${c.firstName} ${c.lastName}") // Ivan Petrov
}
If you accidentally swap them, the compiler won’t save you: the types are the same. But with named arguments, the chance of mixing them up is much lower.
6. val or var: “can be changed” is part of the API
Now comes the moment where a programmer grows up and starts saying scary things like “mutability must be earned.” But without fanaticism: var is not evil; it just opens the door to changes, and changes need to be controlled.
The difference is simple. val in the constructor means the object is created and the property cannot be reassigned (although if a mutable object is stored inside, that’s a separate story—we won’t go there now). var means you can change the property value after creation.
For example, for an expense it usually makes no sense to change id after creation, and often it makes no sense to change amount (an expense record is a fact). So in the model it’s logical to keep these as val. But if we want to allow editing the record (for example, fixing a typo in the title), we can make title a var. The key is that this decision should be deliberate, not “I’ll put var everywhere so I don’t have to think.”
An example of “deliberate mutability”:
class Expense(
val id: Int,
var title: String,
val amount: Int,
val category: String = "other"
)
fun main() {
val e = Expense(id = 1, title = "Cofee", amount = 350) // typo :)
e.title = "Coffee"
println(e.title) // Coffee
}
Here, var title reads like a promise from the class: “The title can be corrected.” And val amount reads like a promise: “We don’t touch the amount; it’s an expense fact.” And that’s exactly what it means that “the constructor is part of the API”: through val/var you communicate the rules for using your type.
7. When a parameter should not be a property
Sometimes you want to pass something temporary into the constructor: for example, “raw text” that’s only needed to compute a normalized value. Or, say, you accept the string " Food " and want to store "food".
Today we’re not doing init yet (that’s the next lecture of the day), but it’s important to understand the idea: sometimes a constructor parameter is just material from which you create state, and the material itself doesn’t need to be stored.
Here’s a micro-example on a familiar topic:
class Category(raw: String) {
val name: String = raw.trim().lowercase()
}
fun main() {
val c = Category(" FoOd ")
println(c.name) // food
}
Why isn’t raw a val raw? Because we don’t need to store “dirty input.” We want to store an already prepared value suitable for logic.
This approach fits well with the idea from the documentation: a parameter without val/var is not a property and does not “live inside the object” on its own.
8. Practice and useful nuances
When you need constructor, and when you don’t
Sometimes you’ll see two variants:
class Person constructor(name: String)
and
class Person(name: String)
The difference is not in meaning but in syntax. Kotlin allows you to omit the keyword constructor if there are no annotations and no visibility modifiers on the constructor. This is normal practice: most classes are written without constructor.
In our course, in 99% of cases we’ll write it compactly:
class Expense(val id: Int, val title: String, val amount: Int)
And the word constructor will come in handy later, when more “grown-up” cases begin (for example, constructor visibility modifiers), but that’s not the topic of this lecture.
Diagram: primary constructor as a contract
It’s useful to mentally picture object creation as a mini data flow: the outside world passes values → the class accepts them by contract → the object appears in the program.
Here’s a simple diagram:
flowchart LR
A["Kod snaruzhi
Expense(...)"] --> B["Primary constructor
(parametry)"]
B --> C["Svoystva ob’ekta
(val/var)"]
C --> D["Ob’ekt gotov k ispol’zovaniyu"]
In this picture, the primary constructor is where you define the contract: what data is required, what is optional (defaults), what will become part of the state (val/var), and what is just input.
Mini-step: an expense list using objects
So we don’t leave everything at “API theory,” let’s take a micro-step in our app: in main() we’ll create a few expenses and print them. No complicated commands—just feel that the model has become readable.
class Expense(
val id: Int,
val title: String,
val amount: Int,
val category: String = "other"
)
fun main() {
val expenses = mutableListOf<Expense>()
expenses.add(Expense(id = 1, title = "Coffee", amount = 350, category = "food"))
expenses.add(Expense(id = 2, title = "Taxi", amount = 900, category = "transport"))
expenses.add(Expense(id = 3, title = "Notebook", amount = 120)) // default category
for (e in expenses) {
println("#${e.id}: ${e.title} — ${e.amount} (${e.category})")
// #1: Coffee — 350 (food)
// #2: Taxi — 900 (transport)
// #3: Notebook — 120 (other)
}
}
You can immediately see that the primary constructor really “works like an API”: it dictates what fields the expense has, what they’re called, and which values you can omit. And named arguments turn creation into almost self-documenting code.
9. Common mistakes
Mistake #1: confusing a constructor parameter with a property and forgetting val/var.
It looks like this: you write class Expense(id: Int, title: String), then try to access e.title, and the compiler says “no such thing.” In reality it’s fair: title was only an input parameter, not part of the state. If the value must live inside the object, make it val title: String right in the constructor or assign it to a property inside the class body.
Mistake #2: making all properties var, because “maybe it’ll be useful.”
This is one of the most expensive habits. When you put var, it’s like leaving the door open: “this can be changed at any time.” Then it turns out that somewhere a value changed, the logic drifted, and you hunt for the culprit like a detective with a magnifying glass. Start with val and switch to var only for what truly must change by meaning.
Mistake #3: too many parameters in the primary constructor and “magic” argument positions.
If a constructor requires 6–8 parameters and you call it positionally (for example, A(1, "x", "y", 10, 20, true)), the code starts to look like a spell that you must not touch or you’ll summon a demon. At the level of this lecture, the simplest rescue is to use named arguments and default values more actively so that only truly necessary things remain required.
Mistake #4: bad parameter names in the constructor.
A constructor is part of the public interface. If you name parameters a, b, x1, s2, you literally force the reader to guess what to pass. It becomes especially painful when you use named arguments: Expense(a = 1, b = "Coffee", x1 = 350). Parameter names should reflect meaning, because they will live in object-creation code.
Mistake #5: not using default values where they are natural, and therefore breeding complexity.
When a parameter is often the same (for example, category "other" or a flag isActive = true), it’s more convenient to give it a default value in the primary constructor than to force every call to repeat the same thing. Kotlin supports this directly: defaults in the primary constructor work the same way as defaults in functions.
GO TO FULL VERSION