1. Introduction
When a program is small, the temptation to keep everything in one .kt file is huge. It’s like “one box for everything”: socks, chargers, documents — while the box is small, it even seems convenient. But as soon as the code grows, the box turns into a black hole: you clearly remember there was a function readIntOrNull() somewhere, but where exactly — not anymore.
Packages (package) in Kotlin are a way to give code a clear “address” so you (and the IDE) can quickly find the functions you need, and identical names don’t fight each other for the right to live in the same space.
It’s important to catch the key idea right away:
package is a “namespace”, a logical grouping of code.
Folders in a project are the “physical organization” of files on disk. Usually they match, but they are different things.
2. What is package: a namespace and an “address” for declarations
If you look at a Kotlin file as a letter, then package is the “deliver to” line. At the top of the file you write:
package app
And that’s it: everything declared in this file (functions, constants, etc.) starts “living” at the address app.
Minimal example: a file in the app package
Let’s imagine we’re making a console game “Guess the Number” (from the mini-project). While everything is simple, we can have a single file Main.kt:
package app
fun main() {
println("The game has started!") // The game has started!
}
Now main formally has a fully qualified name: app.main. Usually you don’t write it like that, but it’s useful to think this way.
One file — one package
In Kotlin, package is defined for the entire file. You cannot declare half the functions in app and the other half in app.util within the same .kt file. If you need a different namespace, create another file.
Top-level declarations “belong” to the package
You’ve already seen that variables and functions in Kotlin can be declared at the top level of a file (outside classes). Such declarations also live in the file’s package. A package is a “home” for declarations, and a file is more like a “container/sheet of paper” where you wrote those declarations down.
3. Fully qualified name: how Kotlin distinguishes identical names
As a project grows, you will almost inevitably write two functions with the same “short” name. For example, format() is a great name, and you’ll want to use it in different places.
From Kotlin’s point of view, name uniqueness is ensured not only by the “function name”, but by the combination:
package + name
(and also the signature, but that’s a separate topic).
Two identical functions in different packages is fine
File 1: src/main/kotlin/app/util/format.kt
package app.util
fun formatScore(score: Int): String {
return "Score: $score"
}
File 2: src/main/kotlin/app/cli/format.kt
package app.cli
fun formatPrompt(text: String): String {
return ">> $text"
}
Both functions have different names (formatScore and formatPrompt), but even if they were both simply called format, Kotlin could still distinguish them by package. The problem won’t start with “existence”, but with “usage” — when you try to call format() from a third place. We’ll handle that carefully via import in the next lecture, but today it’s important to understand the addressing principle itself.
An important nuance: a file is not a scope for name resolution
This sounds like a phrase from a compiler document, but it’s genuinely practical. Kotlin (and the IDE) try to ensure that moving a function to another file in the same package doesn’t break code just because “it’s in a different file now”. The name resolution spec explicitly discusses the idea that “there is no separate file scope” — the package matters, not the particular .kt file.
In plain English: a file is not the “owner” of a function. The owner is the package. So you can think of a package as a “folder in a phone book”: it doesn’t matter which page the number is written on; what matters is which category it’s in.
4. Folders and package: a convention that saves your sanity
Now comes the important practical part: how it’s typically done in Kotlin/JVM projects.
In a Gradle project (and for most of you it’s exactly that), code usually lives here:
src/main/kotlin/
And then the most interesting part begins: inside src/main/kotlin people usually create folders that mirror the package.
Mapping “dots ↔ folders”
There’s a simple association rule:
| In package | On disk |
|---|---|
|
|
|
|
|
|
|
|
That is:
- dots in package turn into “folders”;
- the folder order mirrors the “address”.
For example, if you write:
package app.util
then the file is usually located at:
src/main/kotlin/app/util/FileName.kt
Why this is a “convention”, not a strict law
The Kotlin compiler can technically build a project where the file is in the “wrong” folder (especially if you manually configured source directories). But the IDE and people will suffer.
IntelliJ IDEA can highlight the problem in a style like Package directive doesn't match file location. And this is that rare case where the IDE isn’t being pedantic — it’s actually trying to save you from future chaos.
Analogy: address and warehouse
package is the “address on the envelope” (how to find you logically). Folders are the “location of boxes in the warehouse” (how things are stored physically).
If the address and the warehouse match — you’re happy. If they don’t — you can still find the box, but you’ll do it like a quest hero: “bring the artifact from the basement, but your map is from a different game”.
5. Project-level practice: splitting the “Guess the Number” game into packages
Now we won’t add new language constructs. We’ll take functions you already know and simply lay them out by meaningful “addresses”.
Let’s assume we have logic for:
- number input,
- secret generation,
- the main game loop,
- printing messages to the user.
If you keep everything in one file Main.kt, it will quickly bloat. So let’s split into packages:
- app — entry point and scenario assembly (that is, main)
- app.game — game logic
- app.io — input and validation (reading utilities)
- app.util — small formatting helpers
Let’s draw it as an “address map”:
flowchart TD
A["package app
Main.kt"] --> B["package app.game
Game.kt"]
A --> C["package app.io
Input.kt"]
A --> D["package app.util
Text.kt"]
app: entry point
File: src/main/kotlin/app/Main.kt
package app
fun main() {
println("Welcome to 'Guess the Number'!") // Welcome to 'Guess the Number'!
}
So far there’s not much here. But the idea is: main is the “conductor”. It calls functions from other packages and connects the scenario into a single application.
app.util: text normalization
File: src/main/kotlin/app/util/Text.kt
package app.util
fun normalizeCommand(raw: String): String {
return raw.trim().lowercase()
}
This function is small, but very “package-y”: it’s not about the game, not about reading numbers, but about string processing in general. So it makes sense for it to live in util.
app.io: reading an integer “like a human”
File: src/main/kotlin/app/io/Input.kt
package app.io
fun readIntOrNull(prompt: String): Int? {
print(prompt)
val raw = readln().trim()
return raw.toIntOrNull()
}
Notice: there’s no magic here. It’s the same logic you wrote earlier; it’s just now in a separate file and has a clear address app.io.readIntOrNull.
app.game: secret generation
File: src/main/kotlin/app/game/Secret.kt
package app.game
import kotlin.random.Random
fun generateSecret(from: Int, until: Int): Int {
return Random.nextInt(from, until)
}
Here we again use the already familiar topic Random (you covered it earlier). The important part is that logic related to the game starts living in app.game, and that makes the project more readable: just by the file path you understand “what it’s about”.
6. Package discipline: default package and naming
The default package and why it’s almost always a bad idea
Sometimes you see a file without a package line at the top. This means the file is in the default package.
Technically it works. Practically it’s like “living without an address”: the courier can still call you and ask “so you’re somewhere near the entrance, right?”, but that’s not how a normal life is built.
The main problems with the default package usually don’t show up immediately. At first everything is fine: one file, a second file, a third... And then you suddenly want to:
- split code into subpackages,
- reuse functions in another project,
- understand who is responsible for what,
- avoid name conflicts.
And that’s when the lack of packages starts to bite back.
A good rule for learning and small projects: as soon as you have more than one file, create a proper package, at least package app.
And even for a single file it’s often useful: you get used to discipline and suffer less as the project grows.
Package naming nuances
In the industry there are common conventions:
Package names are written in lowercase, usually separated by dots, for example app.util or com.example.myapp. This form is convenient and readable, and it almost never conflicts with class/function names.
If you really want to name a package MyCoolStuff, stop for a second and imagine living with it six months from now. Most likely you’ll end up with mycoolstuff or my.cool.stuff anyway. Kotlin code is read many times and written once — so it’s better to pick a version right away that doesn’t irritate the eye.
One more point: a package is a logical grouping. Don’t try to make a “package per function”. It’s like a supermarket: if you have a separate shelf for each loaf of bread, you didn’t organize the store — you built a bread museum.
7. Common mistakes when working with package and folders
Mistake #1: the package doesn’t match the file location under src.
This is the most common story: the file is in src/main/kotlin/app/util, but at the top it says package app.utils (an extra s) or even package app. Formally you can even live like this for a while, but the IDE will get confused, navigation will become weird, and the project will start to resemble a drawer where T-shirts are stored in the “spoons” compartment.
Mistake #2: putting everything into one package “because it’s simpler”.
The app package quickly turns into a “junk-drawer package” that contains input, game logic, and formatting. It feels convenient at first, and then you’re afraid to open autocomplete because there are 30 functions with similar names. It’s better to add subpackages by meaning: app.io, app.game, app.util.
Mistake #3: expecting that “one file = one package”.
It’s the other way around: one package almost always consists of many files. A package is a logical area, and a file is just a place where you wrote down part of the declarations. Get used to thinking in packages, not files, otherwise you’ll “search for a function by file name” — not the most pleasant form of archaeology.
Mistake #4: leaving files in the default package “while the project is small”.
It’s a trap. The project is small only until you add a second file and want a bit of order. Then migration begins: moving files, fixing references, relocating directories. It’s much cheaper to create a proper package right away, even if it’s just one.
Mistake #5: weird package names (spaces, uppercase, “random”).
Technically some things might even build (until the first serious conflict), but readability and project culture degrade. Lowercase and clear words are boring, but they work — like most good engineering decisions.
GO TO FULL VERSION