1. Introduction
When we’re just starting to program, it’s natural to store everything in separate variables: it’s simple and feels like math. But as soon as variables become “parts of the same meaning,” everyday chaos begins: it’s easy to mix up values, forget to update them, or pass them in the wrong order. The language doesn’t know these pieces are supposed to live together, so it can’t help you.
Imagine we’re writing a small expense tracker (we’ll return to it today and later). We have an “expense name” and an “amount.” The naive version looks like this:
fun main() {
val title = "Coffee"
val amount = 300
println("$title: $amount") // Coffee: 300
}
As long as it’s just one expense, it seems fine. But now imagine there are many expenses. The “I’ll make title1, amount1, title2, amount2” approach quickly turns into a museum of pain, where exhibits are labeled with a marker: “something like this.”
A slightly more “advanced” beginner option is two parallel lists:
fun main() {
val titles = mutableListOf("Coffee", "Taxi")
val amounts = mutableListOf(300, 1200)
println("${titles[0]}: ${amounts[0]}") // Coffee: 300
}
And here the magic begins: if you delete an element from one list and forget to delete it from the other, the data becomes “out of sync.” The program will keep running—it will just print coffee for 1200 and taxi for 300. That’s not a compiler error; that’s a reality error.
At this point you want to say: “I know for sure that title and amount are one whole. Why doesn’t Kotlin know that?” Answer: because you haven’t told Kotlin that explicitly yet. Classes are exactly a way to say: “This is a single entity.”
Pair as a temporary solution
When it becomes clear that “two variables are one whole,” many people make a logical move: they glue the values into a Pair. This already looks like a normal data structure: one value that contains two fields inside.
An expense scenario using Pair:
fun main() {
val expense: Pair<String, Int> = "Coffee" to 300
println(expense.first) // Coffee
println(expense.second) // 300
}
Pair is genuinely useful: it lets you quickly combine two values and pass them around as one. It’s convenient when you’re making a small one-off bundle, like “name and counter” or “result and message.”
But Pair has a fundamental problem: the names first and second carry no domain meaning. A week later you’ll see pair.second and try to remember: “Is the second one the amount? age? rating? number of kittens?” Sure, you can agree that “second is always amount,” but such agreements usually last exactly until the first tired evening.
To see the difference, it’s helpful to compare the approaches as a small table:
| Approach | What it looks like | What’s good | What starts to hurt |
|---|---|---|---|
| Separate variables | |
simple | no “single whole,” easy to mix up |
|
|
one value | without meaning |
| Class | |
clear field names | you have to declare a type once |
A class is the next step: you create your own data type with normal names, and the code starts reading like text.
Class and object
When you see Int, you perceive it as a ready-made type: a number you can do something with. A class is a way to create your own type in roughly the same style: “this is not two values, this is one object—an expense.”
Technically, a class is declared with the word class. For example, an “empty” class can look like this:
class Expense
But an “empty” class is useless: it’s like a box with nothing inside. So we’ll add fields (properties). Right now we’ll do it in the most straightforward way—via properties in the class body—so we don’t jump ahead into constructor syntax (that will be a separate topic later).
class Expense {
var title: String = ""
var amount: Int = 0
}
Now you can create an object of this class. In Kotlin, unlike some other languages, you don’t write new when creating an object—you just call the class name “like a function.”
fun main() {
val e = Expense()
e.title = "Coffee"
e.amount = 300
println("${e.title}: ${e.amount}") // Coffee: 300
}
What matters here at the “get it and stop being afraid” level:
- Expense is a type.
- e is a variable that holds a reference to an object of type Expense.
- Expense() is the moment a new object (an instance of the class) is created.
- e.title and e.amount are access to the object’s data via the dot.
And now we’ve taken a key step: instead of “two independent variables that you have to keep in your head,” we have “one value that has meaningful parts.”
Tying the idea to the expense app
Now we’ll carefully start translating the idea of classes into our learning context: an app that has expenses. We’re not building architecture or inventing a “correct” model for the ages—we need to feel how a class turns a set of values into a meaningful entity.
Let’s make a simple draft: the Expense class, creating an object, and a print function. Note: the function takes one parameter (an expense), not two (name and amount). That’s already a readability win.
class Expense {
var title: String = ""
var amount: Int = 0
}
fun printExpense(e: Expense) {
println("${e.title}: ${e.amount}")
}
fun main() {
val e = Expense()
e.title = "Coffee"
e.amount = 300
printExpense(e) // Coffee: 300
}
Now compare this to the Pair version. There printExpense would look like: “pass me a pair, and I’ll remember that first is the title.” That means part of the meaning lives only in your head. With a class, the meaning lives in the code.
And one more nice thing: an object can be “passed along” as a single value. For example, you can make a “create expense” function and return an object:
class Expense {
var title: String = ""
var amount: Int = 0
}
fun createExpense(title: String, amount: Int): Expense {
val e = Expense()
e.title = title
e.amount = amount
return e
}
fun main() {
val lunch = createExpense("Lunch", 900)
println("${lunch.title}: ${lunch.amount}") // Lunch: 900
}
So far this looks a bit verbose, and that’s fine: we’re deliberately using the most explicit style so it’s clear what exactly is happening. Kotlin lets you write it shorter, but “shorter” only makes sense after “clear.”
2. Object references and variable behavior
A variable stores a reference to an object
The word “reference” often sounds like the beginning of a lecture after which you want to jump out the window (or at least into the hallway). But here we don’t need theory about memory, addresses, and bytes. We need a practical behavior model so you don’t catch “weird bugs” and think Kotlin is messing with you.
Let’s simplify to an everyday analogy. An object is like a folder on your desk. A variable is like a label with a name that you stick onto the folder. If you stick a second label onto the same folder, you don’t get two folders—the folder is still one; it just has two names now.
Let’s look at the code:
class Box {
var value: Int = 0
}
fun main() {
val a = Box()
a.value = 10
val b = a
b.value = 99
println(a.value) // 99
}
The key line here is val b = a. It does not create a new object. It makes b point to the same object as a. That’s why changing b.value changes the state of one and the same object, and when you read a.value you’ll see 99.
It’s useful to lock this in with a diagram. This is not “real memory,” just a picture so your brain doesn’t resist:
flowchart LR
a[a] --> obj["Box(value=10)"]
b[b] --> obj
After b.value = 99 the object becomes Box(value=99), and both variables see the same thing.
This behavior is not a “Kotlin quirk,” but a basic idea of object types: a variable stores a reference, not “the whole object itself.” This will be the most important foundation for all the next steps.
val and var: can’t reassign, but can mutate
A very common beginner confusion: “if I have val, then the value is immutable.” That’s true for numbers and strings in everyday terms, but for objects you need a clarification: val forbids reassigning the variable, but it doesn’t necessarily forbid mutating the object it points to.
Let’s make an example that shows the difference between “reassign the reference” and “mutate the object”:
class Counter {
var value: Int = 0
}
fun main() {
val c = Counter()
c.value = 5
c.value += 1
println(c.value) // 6
}
Here c is a val, but c.value is a var. That means: the variable c will always point to the same object, but inside the object the field value can be changed.
But this is not allowed:
class Counter {
var value: Int = 0
}
fun main() {
val c = Counter()
// c = Counter() // not allowed: val cannot be reassigned
}
In plain language: val says “you can’t move the label onto a different folder,” but it doesn’t say “you can’t change the documents inside the folder.”
Why does this matter today specifically? Because once you start storing objects in collections, or passing them into functions, or assigning one variable to another, the “I changed it here, but it changed over there” effect suddenly pops up. And that’s almost always a reference question, not mysticism.
“Same data” vs “same object”
One more point where beginners usually put on honest eyes: “But I created two identical objects—why aren’t they the same thing?” Because “same fields” and “same object” are different concepts.
Look:
class Box {
var value: Int = 0
}
fun main() {
val a = Box()
a.value = 10
val b = Box()
b.value = 10
println(a === b) // false
}
The === operator checks whether two variables point to the exact same object. Here they don’t, because we wrote Box() twice—that is, we created two different objects.
Now compare that to “two names for one object”:
class Box {
var value: Int = 0
}
fun main() {
val a = Box()
a.value = 10
val b = a
println(a === b) // true
}
This topic is closely related to == (“value equality”) and === (“reference equality”). You’ve already encountered this idea before, and today it’s important to keep only the practical part: === helps you check whether it’s “one folder with two labels” or “two separate folders.”
For “data equality” we won’t draw far-reaching conclusions yet: for a regular class without additional logic, == is not required to compare fields the way you might want. So today we keep the focus on references and on how that affects state changes.
3. Common mistakes when working with objects and references
Mistake #1: thinking that b = a creates a copy of the object.
This expectation comes from being used to numbers and strings: “assigned it—so I got my own independent value.” But with objects, assignment copies the reference; it doesn’t make a new object. If you need an independent entity, you must create a new object explicitly (for example, call Expense() again or another constructor).
Mistake #2: believing that val makes an object “immutable.”
val protects the variable from reassignment, but it does not forbid changing the object’s var properties. That’s useful, but sometimes surprising: “why is it changing if it’s val?” Because it’s not the reference that changes, but the object’s state. If you want fewer surprises, a helpful habit is to start with val references and add mutability inside the object very deliberately.
Mistake #3: overusing Pair where there is already domain meaning.
Pair is great as a temporary glue, but as soon as you catch yourself thinking “first is the expense title,” that’s a signal: it’s time to give the entity a name (Expense) and normal properties. Otherwise the code turns into a set of riddles over time: “and what is second here?”
Mistake #4: trying to “stuff everything into a class” right away without understanding boundaries.
On the first day of OOP, you often want to make a class that stores data, prints itself, reads input, sorts a list, and also knows how to brew coffee. At the start, keep a class as a data model (fields)—that alone is enough to win in readability and reduce the number of mistakes.
Mistake #5: ignoring the “one object or two” check when debugging.
When something “suddenly changes in the wrong place,” the best quick test is to check a === b. If it’s true, then you really are working with one object, just through two names. That doesn’t fix the bug by itself, but it instantly explains why it’s possible.
GO TO FULL VERSION