1. Why scopes are needed
When you write a small 20-line program, usually everything lives in main, and it seems like no special rules are needed: “I can already see the whole code.” But as soon as you start extracting logic into functions (and that is the right thing to do), more and more names appear in the file: printMenu, readChoice, sumExpenses, formatMoney, and so on. At that moment your brain starts working like a compiler: “what of this can I touch? where is it declared? why is it not visible here?”
So that your brain does not overheat (and the compiler does not start throwing Unresolved reference at you), Kotlin has two ordering mechanisms:
- Visibility modifiers (public, private) answer the question: who can use this declaration from the outside?
- Scope answers the question: in what part of the code does the name exist and remain accessible?
On the surface these words look similar, but the meaning is different. Let’s separate them carefully.
Visibility: public and private
When we say “visibility,” we are discussing access boundaries. This is no longer about where a variable is declared, but about who is allowed to access it. Imagine your file is a small “function shop.” Some functions are the storefront: a user walks in and sees them. And some are service rooms: only staff goes there, and the customer has nothing to do there (and it is even harmful if they get in).
Within this lecture, we only need two modifiers:
- public — accessible “from the outside.” At the file (top-level) level, this is the default, meaning you usually do not need to write public.
- private — accessible only within this file (if it is a top-level function or variable).
This is especially useful when you have helper functions: they are needed to implement a scenario, but you do not want someone to accidentally start calling them as an “official API.”
In Kotlin, a very typical visibility approach is to hide input helper functions as private so as not to clutter the file’s “public storefront”: you can see this approach even in template-writing practices, where they do private fun readInt() = ....
Mini example: a public function and a private helper
fun main() {
runApp()
}
private fun runApp() {
printHeader()
println("Application started")
}
private fun printHeader() {
println("=== BudgetBuddy ===") // === BudgetBuddy ===
}
Here main() is public by default (we do not write it, but it is implied), and runApp() and printHeader() are our internal details. If the file were part of a large project, we would not want someone “outside” to call printHeader() directly.
2. Scope: where a name exists
Now about scope — this is no longer about “is it allowed,” but about “is it visible at all.” Even if something is public, it does not become accessible everywhere on the planet: the name is still accessible only within a specific area of code.
The most common beginner thought sounds like: “But I declared the variable, why can’t I use it below?” Answer: because you declared it inside a block, and the block ended — the variable “died” (don’t worry, this is a normal and even useful death).
In Kotlin, scopes are most often defined by curly braces { ... }. And these are not decorative braces, but actual boundaries of a name’s lifetime.
Example: a variable lives only inside an if
fun main() {
val x = 10
if (x > 0) {
val msg = "x is positive"
println(msg) // x is positive
}
println(msg) // Compilation error: msg no longer exists here
}
msg is declared inside the if block. After the closing }, the name msg disappears: you cannot refer to it, even if you really want to.
The same principle for while and for
fun main() {
var sum = 0
for (i in 1..3) {
val add = i * 10
sum += add
}
println(sum) // 60
println(add) // Error: add is visible only inside the loop body
}
The variable add exists only inside the loop body. This protects you from accidentally using “temporary” variables where they no longer make sense.
3. Useful nuances
private/public and scope are not the same thing
It is easy to get confused here, so let’s lock it in with a clear analogy. Imagine you have keys and walls.
Scope is the walls of a room. If you leave the room, you do not see the things that remain inside.
Visibility (private/public) is the keys to the door.
Even if an object is in the room, you may not have the right to enter.
That is:
- a name can be in scope (it “lives here”), but be inaccessible due to private (for example, from another file);
- a name can be public, but still not exist at the current location in code (if you left the block).
So you don’t keep this in your head as a mush, it is helpful to look at a table.
| What we are discussing | Question | Example | What “controls” it |
|---|---|---|---|
| Scope | “Where does the name exist?” |
|
Curly braces, code structure |
| Visibility | “Who can use it?” |
|
Modifiers private/public |
Local functions and scope
In the previous lecture, you learned about local functions: functions declared inside another function. Now is the right time to understand them through the lens of scope: a local function is visible only inside the outer function. Outside it, it does not exist.
This is often very convenient: you do not litter the file with a dozen “helperSomething” functions if they are needed only in one scenario.
Example: a local function for formatting money
fun main() {
printReceipt(totalCents = 2599)
}
fun printReceipt(totalCents: Int) {
fun formatMoney(cents: Int): String {
val dollars = cents / 100
val rest = cents % 100
return "$dollars.${rest.toString().padStart(2, '0')}"
}
println("Total: ${formatMoney(totalCents)}") // Total: 25.99
}
formatMoney is an “internal employee.” It exists only inside printReceipt. You cannot call it from the outside (and that is a plus: fewer ways to accidentally break something).
4. Name shadowing
If you like looking for tricks in everything, you have probably already asked: what happens if there are multiple variables with the same name in scope?
You can declare a variable with the same name as another variable at a higher level. This is called name shadowing (shadowing). The compiler often allows it, but readability almost always suffers.
The main danger is not that “the program does not work,” but that later you read the code and think: “which x is this x?”
Example: same names in different blocks
fun main() {
val count = 10
run {
val count = 3
println(count) // 3
}
println(count) // 10
}
Inside the run { ... } block, count is a different count. The outer one did not go anywhere, but it is “hidden” inside the block. Technically this can be necessary, but in educational and applied projects it is most often just accidental confusion.
5. The BudgetBuddy project and visibility order
Now we will carefully apply private/public and scope in practice. Let’s have a simple console app BudgetBuddy: we store expenses in an array, add new amounts, and print statistics. We do this in a single file specifically so we do not drift into project structure and packages.
Let’s agree on style right away: from the outside we only need the entry point main(). Everything else is implementation detail, so it makes sense to make it private, so the file looks like a neat “mini-module.”
Step 1: the file’s storefront — only main()
fun main() {
runBudgetBuddy()
}
private fun runBudgetBuddy() {
println("=== BudgetBuddy ===") // === BudgetBuddy ===
}
Even at this step, the file reads nicely: main starts the scenario, and the scenario is hidden inside.
Step 2: add state and show variable scope
We will store expenses in an IntArray, where the number is an amount in cents (so we do not deal with Double and precision).
fun main() {
runBudgetBuddy()
}
private fun runBudgetBuddy() {
val expenses = IntArray(5)
var size = 0
println("Let's add test expenses...")
expenses[0] = 199
expenses[1] = 550
size = 2
println("Entries: $size") // Entries: 2
}
Here expenses and size live only inside runBudgetBuddy. This is normal: it is internal scenario state.
Step 3: split into functions and hide helpers
Let’s add a menu and a command choice. Note: we are not building a “perfect product,” we are practicing visibility and name scopes.
fun main() {
runBudgetBuddy()
}
private fun runBudgetBuddy() {
println("=== BudgetBuddy ===") // === BudgetBuddy ===
while (true) {
printMenu()
val cmd = readln().trim()
if (cmd == "exit") return
println("Command: $cmd") // Command: ...
}
}
private fun printMenu() {
println()
println("Enter a command: add / list / exit")
}
printMenu() is a pure helper. Nobody outside the file needs it, so private is a perfect fit.
By the way, the habit of marking such functions as private is useful even in “single-file” tasks: you prevent your file from turning into a dump of “public random functions.” This approach with private helper functions is often used in input templates (for example, private fun readInt()), so you do not multiply public declarations.
Step 4: blocks and scope inside if/else if
And here you can clearly see how blocks and scope work.
fun main() {
runBudgetBuddy()
}
private fun runBudgetBuddy() {
val expenses = IntArray(10)
var size = 0
while (true) {
printMenu()
val cmd = readln().trim()
if (cmd == "add") {
val added = addExpense(expenses, size)
size += added
} else if (cmd == "list") {
printExpenses(expenses, size)
} else if (cmd == "exit") {
return
} else {
println("Unknown command: $cmd")
}
}
}
private fun printMenu() {
println()
println("Enter a command: add / list / exit")
}
Look closely: the variable cmd lives inside the loop body of while. And the variable added lives only inside the if block (cmd == "add") { ... }. This is good: we cannot accidentally use added in the "list" branch.
Now let’s add the functions themselves (short and clear):
private fun addExpense(expenses: IntArray, size: Int): Int {
if (size >= expenses.size) {
println("The array is full, you cannot add more")
return 0
}
print("Enter an amount in cents: ")
val cents = readln().trim().toInt()
expenses[size] = cents
return 1
}
private fun printExpenses(expenses: IntArray, size: Int) {
println("Expenses:")
for (i in 0 until size) {
println("- ${expenses[i]} cents")
}
}
Notice a small but important thing: size in addExpense is a parameter. Parameters behave like val: you can’t reassign them. But expenses[size] = cents is allowed, because that changes an element of the array, not the parameter itself.
But why is this change visible in runBudgetBuddy? Remember val alias = original from the lecture on arrays: assignment doesn’t copy the array, it gives the same array a second name. Function arguments work the same way: when you call addExpense(expenses, size), the parameter expenses gets a reference to the very same array that was created in runBudgetBuddy. That’s why an element written inside the function “shows up” outside as well. And size is just a number: the function gets a copy of its value and can’t change the size variable in runBudgetBuddy. That’s why addExpense returns 1 or 0, and runBudgetBuddy increases size itself: size += added.
Step 5: hide formatting and avoid name shadowing
Let’s make money formatting a private function. It could be local, but we will need it in several places, so let it be private at the file level.
private fun formatMoney(cents: Int): String {
val dollars = cents / 100
val rest = cents % 100
return "$dollars.${rest.toString().padStart(2, '0')}"
}
private fun printExpenses(expenses: IntArray, size: Int) {
println("Expenses:")
for (i in 0 until size) {
println("- ${formatMoney(expenses[i])}")
}
}
What matters here is that rest is a name inside formatMoney. It does not “leak” outward. And that is great: the fewer names live for a long time, the less likely you are to accidentally step on them elsewhere.
Mini diagram: how to read a file with private helpers
When you structure the file so that only main() sticks out, and everything else is detail, reading becomes linear: “start → scenario → helpers.”
flowchart TD
A["public main()"] --> B["private runBudgetBuddy()"]
B --> C["private printMenu()"]
B --> D["private addExpense(...)"]
B --> E["private printExpenses(...)"]
E --> F["private formatMoney(...)"]
Such a file is easier to maintain: you immediately see which function is the “main” one, and which ones are supporting.
6. Common mistakes
Mistake #1: confusing private with scope, expecting private to “hide a variable from a neighboring block.”
Sometimes it feels like if you make something private, it will disappear “somewhere nearby.”
But private/public is about access between files (and other external parts of the project), not about blocks { ... }.
A block is enforced by scope: a variable inside if is not visible outside not because it is “private,” but because the block ended.
Mistake #2: declaring a variable in a block and then trying to use it after the block.
A classic: you read input in an if, create a val value, and below you want to print it.
The compiler fairly says Unresolved reference.
The solution is usually simple: declare the variable before the block, and inside the block assign it.
Then the name will live longer, and you consciously choose its lifetime.
Mistake #3: name shadowing “for convenience,” which later turns into confusion.
Beginners sometimes redeclare val x inside a block because “it’s easier for me this way.”
Yes, easier now — but 15 minutes later you will be figuring out which x is used in a given line.
It is better to use different names: userChoice, menuChoice, newChoice — longer, but your brain will not have to work like a detective.
Mistake #4: making everything public just because “it works that way.”
If you leave all top-level functions public, the file turns into a set of random “external promises.”
Even if the project is small right now, the habit of hiding helpers as private helps discipline design:
there is an entry scenario and there is an internal kitchen. As a result, the code is easier to read and harder to accidentally use the “wrong” function.
Mistake #5: creating too many variables with large scope “just in case.”
Sometimes, to defeat visibility errors, a beginner declares everything at the beginning of a function:
var a, var b, var c
— and then assigns them along the way.
It works, but makes the code muddy: it is unclear when a variable is actually needed and what state it is in.
It is much nicer to keep variables as close as possible to where they are used and let scope limit their lifetime.
GO TO FULL VERSION