Packages, Files and Imports
Kotlin code is grouped into packages declared at the top of each file, one file may hold several top-level declarations, and imports bring names from other packages into view.
Resolve names across files and packages without relying on file order.
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.