1. Primary constructor and properties
When we first see a class in Kotlin, it feels like some kind of “special kind of function” with curly braces. And that’s almost true: creating an object really does look like calling a function. Primary constructor is exactly that “front door” through which we pass initial values into a new object. It’s written right in the class header, immediately after the name.
In Kotlin, the primary constructor is declared in the class header: after the name, in parentheses. If there are no annotations or visibility modifiers, the keyword constructor can be omitted.
Let’s look at the most “straight-on” variant — with an explicit constructor (it’s easier to see where it starts and ends):
class Expense constructor(title: String, amount: Int)
fun main() {
val e = Expense("Coffee", 300)
println(e) // Expense@<some_hash>
}
Yes, this code will compile, and the object will be created. But there’s an important detail: title and amount have not become properties yet. They are just parameters that came “as input”, and then… they didn’t get stored anywhere, because we didn’t tell Kotlin that we want to keep them.
To show the problem a bit more clearly, imagine we try to do this:
class Expense constructor(title: String, amount: Int)
fun main() {
val e = Expense("Coffee", 300)
// println(e.title) // not allowed: title is not a property
}
The compiler is right: the object has no title property, because we didn’t declare it.
Constructor parameter vs. property
At this point, beginners often have a small drama: “But I passed title into the class — why can’t I read it via dot access?” The pragmatic answer: because Kotlin distinguishes between “a value passed at creation time” and “a value stored inside the object”. If you want the parameter to become part of the object, you must declare it as a property — i.e., add val or var.
In Kotlin, the primary constructor can declare parameters as properties: val creates a read-only property, var creates a mutable one. Such properties are stored in the instance and are accessible from outside via dot notation.
Let’s make a proper version of Expense:
class Expense(val title: String, val amount: Int)
fun main() {
val e = Expense("Coffee", 300)
println(e.title) // Coffee
println(e.amount) // 300
}
Now title and amount are properties, they live inside the object, and we can read them.
To reinforce the difference, a small table is handy:
| Constructor syntax | Is it an object property? | Can you access it as obj.x? | Where can it be used |
|---|---|---|---|
|
no | no | only inside the class body (if there is a body at all) |
|
yes (read-only) | yes | both inside the class and from outside |
|
yes (mutable) | yes | both inside the class and from outside |
Now a real-world example that often comes up: we want to accept “raw input”, process it (for example, trim()), and only then save it into a property. In that case, the constructor parameter does not have to be a property — it can be just an “input argument”:
class User(nameInput: String) {
val name: String = nameInput.trim()
}
fun main() {
val u = User(" Ann ")
println(u.name) // Ann
// println(u.nameInput) // not allowed: it's not a property
}
This is a useful mental model: a parameter is what came in at creation time, and a property is what we decided to keep inside the object.
2. Creating objects without new
When we create an object, we write the class name and parentheses, as if we were calling a function. And that’s not an accident: the constructor is indeed invoked like an “instance factory function”. Kotlin has no new keyword — an object is created simply via ClassName(...).
Let’s make an example in the style of our app (a console expense tracker). For now we’ll just create a couple of expenses and print them:
class Expense(val title: String, val amount: Int)
fun main() {
val coffee = Expense("Coffee", 300)
val taxi = Expense("Taxi", 1200)
println("${coffee.title}: ${coffee.amount}") // Coffee: 300
println("${taxi.title}: ${taxi.amount}") // Taxi: 1200
}
Notice a subtle point from the “object reference” model. Even if a variable is declared as val, it means “the reference cannot be reassigned”, not “the object is magically frozen”. Right now our properties are also val, so the object ends up being “stable”.
Here’s a mini-demonstration of “two names for one object”, so your brain doesn’t forget the model:
class Expense(val title: String, val amount: Int)
fun main() {
val a = Expense("Coffee", 300)
val b = a
println(a === b) // true
}
a === b is true, because it’s the same reference. This knowledge will come in handy when var properties appear, but today our goal is specifically constructor syntax.
3. Default values
As soon as a class has more than two fields, we get a new pain: “Do I have to pass everything every time, even if some values are typically the same?” Kotlin solves this exactly the same way as in functions: default values.
In a primary constructor, you can specify default values right next to parameters/properties. If a value is not provided at creation time, the default will be used.
Let’s add a category to our Expense and make it default (as a plain string, no extra complexity):
class Expense(
val title: String,
val amount: Int = 0,
val category: String = "OTHER"
)
fun main() {
val e1 = Expense("Coffee")
val e2 = Expense("Taxi", 1200)
val e3 = Expense("Lunch", 900, "FOOD")
println("${e1.title}, ${e1.amount}, ${e1.category}") // Coffee, 0, OTHER
println("${e2.title}, ${e2.amount}, ${e2.category}") // Taxi, 1200, OTHER
println("${e3.title}, ${e3.amount}, ${e3.category}") // Lunch, 900, FOOD
}
The point of defaults here isn’t to “hide the problem”. The point is to make object creation convenient where values really are often the same, while not smearing magic numbers and strings all over the codebase.
One more practical point: default values are a way to create a “minimally valid” object without extra noise. For example, if in our add command the user may omit the category, we can safely create the object with "OTHER".
4. Named arguments
When a constructor has several parameters of the same type (for example, two strings in a row), it’s very easy to mix up their order. In a human head it’s “well, it’s obvious”, in a computer head it’s “ha-ha, you passed a string into a string — totally valid”. To reduce such mistakes, Kotlin allows calling a constructor with named arguments — just like functions.
Named arguments are especially useful in two situations: when there are many parameters and when there are defaults. Then the call becomes self-documenting: you can read it almost like a sentence in plain language.
class Expense(
val title: String,
val amount: Int = 0,
val category: String = "OTHER"
)
fun main() {
val e = Expense(
title = "Books",
amount = 1500,
category = "EDUCATION"
)
println("${e.title}: ${e.amount} (${e.category})") // Books: 1500 (EDUCATION)
}
Now it’s hard to “accidentally break” the call, because the meaning of the parameters is written right in the code.
Named arguments combine perfectly with defaults: you can specify only what you need and not worry about “holes” in the middle of the argument list:
class Expense(
val title: String,
val amount: Int = 0,
val category: String = "OTHER"
)
fun main() {
val e = Expense(title = "Coffee", category = "FOOD")
println("${e.title}, ${e.amount}, ${e.category}") // Coffee, 0, FOOD
}
Note: we skipped amount, and that’s fine, because it has a default value.
5. A readable class header
The first two fields usually fit on one line, and everything looks nice. But life quickly brings a third parameter, then a fourth… and suddenly the class header becomes wider than the screen, and you can only read it with horizontal scrolling. That’s why it’s useful to agree in advance with your future self on how you’ll format the constructor.
A good beginner style is to put parameters on separate lines if there are more than two or if they are long. This isn’t “beauty for beauty’s sake” — it’s about reducing cognitive load: when code is easy to scan with your eyes, there are fewer mistakes in it.
class Expense(
val title: String,
val amount: Int = 0,
val category: String = "OTHER"
)
One more important point: if a parameter should not be accessible from outside, don’t make it a property “out of habit”. Sometimes you want to put val everywhere — “just in case”. But that unnecessarily expands the class API. Try to keep only the truly needed model fields in the header.
A small diagram of what happens when an object is created (very simplified, but useful for your mental model):
flowchart TD
A["Expense(...)"] --> B["Primary constructor receives arguments"]
B --> C["val/var parameters become properties"]
C --> D["Object created; dot access: e.title, e.amount"]
This diagram is about the part we’re studying today: “passed in → stored as properties → read via dot access”.
6. Migration from Pair to the Expense class
Before classes, we often did this: one expense is a Pair<String, Int>, where first is the name and second is the amount. It worked, but it read like “a note on the fridge”: the meaning is there, but you have to remember it. Now we’ll replace it with Expense(title, amount, category).
I’ll show a very small fragment of “how it was” (roughly, in our CLI expense tracker):
fun main() {
val expenses = mutableListOf<Pair<String, Int>>()
expenses.add("Coffee" to 300)
val (title, amount) = expenses[0]
println("$title: $amount") // Coffee: 300
}
Now “how it will be”. Let’s create a class and a list of objects:
class Expense(val title: String, val amount: Int)
fun main() {
val expenses = mutableListOf<Expense>()
expenses.add(Expense("Coffee", 300))
val e = expenses[0]
println("${e.title}: ${e.amount}") // Coffee: 300
}
From the point of view of list operations, nothing magically changes: MutableList is still there. But reading becomes human: e.title instead of pair.first. That’s the “profit” of a domain model.
Now let’s add a default category so that our add command can be simpler:
class Expense(
val title: String,
val amount: Int,
val category: String = "OTHER"
)
fun main() {
val expenses = mutableListOf<Expense>()
expenses.add(Expense("Coffee", 300, category = "FOOD"))
expenses.add(Expense("Taxi", 1200)) // category = OTHER
for (e in expenses) {
println("${e.title}: ${e.amount} (${e.category})")
// Coffee: 300 (FOOD)
// Taxi: 1200 (OTHER)
}
}
This already looks like a starting point for a real app: we can store data in a structured way, and input/commands in main will just create objects.
7. Common mistakes when declaring classes and the primary constructor
Mistake #1: forgot val/var and expected the parameter to become a property.
A very common situation: you wrote class Expense(title: String, amount: Int) and then wondered why e.title doesn’t exist. There’s only one fix: if a field must be accessible via dot notation and stored in the object — declare it as val title: String or var title: String in the header. If a field is needed only as “input”, leave it without val/var, but then explicitly save it into a property inside the class.
Mistake #2: made everything var because “it might come in handy”.
This isn’t a syntax error, but it’s a logical time bomb. The more var you have, the more places where the object can change unexpectedly, and the harder it is to debug “why the amount became 0”. At the start, it’s better to choose val as the default and add var only when you can honestly answer: “Yes, by meaning this field must change after the object is created”.
Mistake #3: mixed up the order of arguments in the constructor.
When a constructor has several parameters, especially of the same types, positional arguments are easy to swap. The compiler won’t save you: String in place of String looks valid. So where meaning matters more than typing speed, use named arguments: Expense(title = "...", amount = ...). This noticeably reduces the number of silent bugs.
Mistake #4: overused default values and “hid the meaning”.
Defaults are convenient, but you can overdo them: when a class has 8 parameters and 7 of them have default values, the object starts getting created “somehow by itself”, and it becomes unclear what is actually important. A good check: if a parameter is always important (for example, the expense amount), it probably should not have a default, so the error is caught immediately at creation time.
Mistake #5: an overly long class header on one line.
Kotlin syntax allows it, but your eyes don’t have to. If the constructor doesn’t fit on one line without horizontal scrolling, move parameters onto separate lines. This isn’t “cosmetic”: readability directly affects the number of bugs, especially when you’re learning and keeping a lot of new things in your head at once.
GO TO FULL VERSION