Skip to the workspace
Pebellslearn by building
Introduction to Kotlin  ›  Lesson

Packages, Files and Imports

Code Organization 12 minKotlin 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.

kotlin / Packages, Files and Imports

Explore each scene at your own pace.

01 · The rule

The rule

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 name cafe.orders.…, so Order is really cafe.orders.Order.
  • import cafe.menu.Menu — lets you write Menu instead 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.kt even though it holds Order and orderTotal. 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.

Scene 1 of 5
Hover to wake the cannons. Drag to move, or use arrow keys when focused. Press Enter to fire a shot.