Packages, Files and Imports
The café app starts as one file. A month later it has orders, a menu, loyalty points and receipts, and scrolling to find anything takes forever. Kotlin gives you packages and imports to keep a growing codebase tidy without much ceremony.
The rule
package says where I live; import says whom I borrow.
A package is a named group of declarations. The package line comes first in a file, before anything else except comments:
package cafe.orders
import cafe.menu.Menu
import kotlin.math.roundToInt
class Order(val drink: String, val cups: Int)
fun orderTotal(order: Order, menu: Menu): Int =
(menu.priceOf(order.drink) * order.cups).roundToInt()What each part tells you:
package cafe.orders— everything in this file has the full namecafe.orders.…, soOrderis reallycafe.orders.Order.import cafe.menu.Menu— lets you writeMenuinstead of the full name.import cafe.menu.*brings in everything from that package.- Several top-level declarations per file. Unlike Java, Kotlin does not demand one public class per file. Functions and constants can live at the top level, outside any class.
- File name is free. The file could be
Orders.kteven though it holdsOrderandorderTotal. Naming it after its main class is a convention, not a rule.
The folder layout usually mirrors the package: src/main/kotlin/cafe/orders/Orders.kt. Kotlin allows a mismatch, but the convention helps people find things.
Some packages, such as kotlin.*, kotlin.collections.*, kotlin.text.* and kotlin.io.*, are imported automatically. That is why println and listOf work without any import line.
If two imports share a name, rename one with as: import cafe.menu.Item as MenuItem.
The shortcut
To read any name in a file, look up: first the declarations in the file itself, then the package line (same package, no import needed), then the import lines, then the default imports.
Look in this file
Orders.ktdeclaresOrderandorderTotal, but notMenu.
A typical mistake is putting import above package. The package line must come first.
Drills
Answer fast — trust the rule.
Which line must come first in a Kotlin file, before any imports?
A file in package cafe.orders declares class Order. What is its full name?
Which statement about Kotlin files is true?
Two packages both have a class Item. How can one file use both?
Remember
packagesays where a file lives;importsays what it borrows.- One file can hold many top-level declarations; the file name is free.
- Read names upward: this file, this package, imports, default imports.
