Skip to content
Tutorials Center
My learning

Topics

Lesson 75 of 134 ยท Idiomatic Kotlin

Packages and Imports

Learn Kotlin packages and imports - package declarations, import aliases, wildcard imports, default imports, top-level declarations and file organization, with runnable examples and real errors.

Every program that grows past one file needs a way to name things without collisions and to say which parts are meant to be used from outside. Kotlin solves the naming half with packages and imports, and it does so with less ceremony than Java: no one-class-per-file rule, no required folder layout, and functions that live directly in a file without any class around them.

This lesson explains how a file declares its package, how import brings names into scope, how aliases resolve clashes, what Kotlin imports for you automatically, and how to organize a real code base. The runner here compiles a single file, so most multi-file layouts are shown as read-only text, while every rule about imports is demonstrated with runnable code.

What a package is

A package is a namespace: a dotted name such as com.example.shop that prefixes the declarations in a file. Two files can both define a class called Order as long as they live in different packages, because their full names (com.example.shop.Order and com.example.billing.Order) differ.

A file declares its package on its first line (comments and annotations may come before it):

Kotlin
// read-only example: shop/Order.kt
package com.example.shop

class Order(val id: Int)

fun newOrder(id: Int) = Order(id)

Everything declared in that file, classes, functions, properties, belongs to com.example.shop. If a file has no package line, its declarations are in the root package, which is fine for scripts and for the examples in this tutorial, but real projects always use named packages.

Unlike Java, Kotlin does not require the directory structure to match the package. The compiler does not care that Order.kt sits in src/main/kotlin/com/example/shop/. Still, the convention is to mirror the package in the folders (omitting a common root prefix if you like), because tools and teammates expect it. You may also put several classes in one file, and name the file after its main content or after the theme if it holds many small things (Orders.kt, Extensions.kt).

Package names are written in lowercase, usually as a reversed domain name (com.example.shop), without underscores.

Importing names

Declarations in the same package see each other directly. To use something from another package you either write its full name every time or import it once at the top of the file.

Kotlin Full names versus imports

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

Both spellings do the same thing. Fully qualified names are handy for a single use or for resolving a clash, but repeated java.time.LocalDate becomes noise, so import what you use often.

You can import:

  • a class, interface or object: import java.time.LocalDate
  • a top-level function or property: import kotlin.math.sqrt
  • a member of an object or an enum entry: import kotlin.math.PI (PI is a top-level constant), or import java.util.concurrent.TimeUnit.SECONDS
  • everything in a package with a wildcard: import kotlin.math.*

Imports must come right after the package line and before any other declaration. Put one after your code and the compiler refuses:

Kotlin Imports must come first (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

The compiler reports error: syntax error: imports are only allowed in the beginning of file. Move the import to the top and it compiles.

Wildcards: convenient, but use them sparingly

import kotlin.math.* brings every public name from that package into scope. It saves typing in a file that uses many of them (math code is the classic case), but it hides where a name comes from and can create ambiguities when two wildcard imports provide the same name. IntelliJ IDEA collapses imports into a wildcard on its own once you use around five names from one package, but you can turn that off. Prefer explicit imports in code other people read.

Default imports

You have been using names like println, String, listOf and Regex without importing them. Kotlin automatically imports a set of packages into every file:

Package Examples
kotlin.* Int, String, Any, println, require, lazy, Pair
kotlin.annotation.* Target, Retention
kotlin.collections.* List, Map, listOf, mapOf
kotlin.comparisons.* compareBy, maxOf, minOf
kotlin.io.* println, readln
kotlin.ranges.* IntRange, until
kotlin.sequences.* Sequence, sequence
kotlin.text.* Regex, buildString, uppercase
java.lang.* (on the JVM) Thread, StringBuilder, Math
kotlin.jvm.* (on the JVM) @JvmStatic, @JvmField

Anything outside that list (kotlin.math, kotlin.time, kotlin.random, java.util, java.time, java.io) needs an explicit import. This is why sqrt fails without import kotlin.math.sqrt, while maxOf does not.

Kotlin A missing import (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

The compiler says error: unresolved reference 'sqrt'. The fix is import kotlin.math.sqrt, or writing kotlin.math.sqrt(16.0). Your IDE offers to add the import with one keystroke; it does not guess silently, because several packages may contain the same name.

Name clashes and import aliases

What if two packages export the same simple name? The JDK has both java.util.Date and java.sql.Date. Importing both is an error:

Kotlin Two imports, one name (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

You get error: conflicting import: imported name 'Date' is ambiguous. (reported on both import lines, followed by follow-on errors where Date is used). Kotlin's answer is an import alias: import ... as NewName. The alias is the only name the file uses for that declaration.

Kotlin Resolving clashes with as

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

Aliases are purely a compile-time convenience: no new type is created. They are also a good tool when a library's name is awkward, or when you must use two classes both called Result or Entry. For long generic types inside one file, a type alias (typealias) is the sibling feature; the difference is that import ... as renames a declaration only within the file, while typealias declares a new name that other files can import.

Top-level declarations

In Java everything lives inside a class. In Kotlin, functions and properties can be declared at the top level of a file, and they belong to the package, not to a class.

Kotlin Top-level functions, properties and constants

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

main itself is a top-level function, and so is println. On the JVM, the compiler packs the top-level members of Shop.kt into a generated class called ShopKt; that is why this runner starts the program with MainKt, the class generated from main.kt. Java callers see ShopKt.label("x"). You can change that name with @file:JvmName("Shop") as the first line of the file (this is covered in Java Interoperability).

Top-level members are the natural home for small utility functions, constants and extension functions. You no longer need final class StringUtils with a private constructor. Do not overdo it, though: a top-level mutable var is global state, with all the usual problems, so keep those private and rare.

Visibility is tied to files and modules

Top-level declarations default to public. private means "visible inside this file", which is the usual way to hide helpers. internal means "visible inside the same module" (one Gradle or Maven module). The details are in Visibility Modifiers. There is no Java-style package-private: the package itself does not restrict access, which is a common surprise for Java developers. If you want to hide something from the rest of a module, private in the file or internal are the tools you have.

Organizing files and packages

A layout that works well for a small to medium project:

TEXT
src/main/kotlin/
  com/example/shop/
    Main.kt              // fun main()
    model/
      Order.kt           // data classes: Order, OrderLine
      Customer.kt
    service/
      OrderService.kt
      PriceCalculator.kt
    util/
      Extensions.kt      // fun String.slugify(), fun Money.format()

Guidelines professionals follow:

  • One topic per file. Several small, related classes may share a file (a sealed hierarchy with its subclasses should), but a file with unrelated classes is hard to find things in.
  • Name the file after its main class. If a file holds one public class, call the file by that class's name (OrderService.kt). A file of top-level functions gets a descriptive plural (StringExtensions.kt).
  • Package by feature or by layer, then be consistent. Large apps often group by feature (shop.orders, shop.billing) because changes tend to touch one feature at a time.
  • Avoid cyclic dependencies between packages. If model imports service and service imports model, the design has a loop; extract a shared package or reverse one dependency.
  • Keep the public surface small. Mark everything that is not used elsewhere as private or internal.

Because only one file can be compiled in this tutorial's runner, a package line breaks the run. The program is then compiled into the class demo.MainKt, but the runner starts MainKt, so Java reports Error: Could not find or load main class MainKt and Caused by: java.lang.ClassNotFoundException: MainKt. That is a limit of this environment, not of Kotlin: in a real project the build tool knows the full main-class name. Leave out the package line in the examples you try here.

Writing main in a package

In a real project, main lives in some package like any other function. The entry point is then com.example.shop.MainKt (the file Main.kt, package com.example.shop). With Gradle you set it with application { mainClass.set("com.example.shop.MainKt") }; from the command line you would run java -cp out com.example.shop.MainKt. A Kotlin file may also contain several main functions, as long as they are in different files (each file gets its own class), which is useful for small experiments next to real code.

Kotlin
// read-only example: Main.kt in a project
package com.example.shop

import com.example.shop.model.Order
import com.example.shop.service.OrderService
import com.example.shop.util.slugify

fun main() {
    val service = OrderService()
    val order: Order = service.create("Ada Lovelace")
    println("order for ${order.customer.slugify()}")
}

The last two imports are ordinary names from other packages; slugify would be an extension function, imported like any other top-level function. Without the import, the compiler would not apply the extension, even though the function exists in the project.

Imports are sorted and cleaned by tools

You rarely write imports by hand. The IDE adds them when you accept a completion, can remove unused ones (the compiler only warns about them) and sorts them in a conventional order. Reformatting in IntelliJ IDEA or Android Studio does this, and a linter such as ktlint can enforce it in CI. Do not spend time ordering imports yourself.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Which packages does Kotlin import into every file automatically?

    A fixed list of kotlin packages (and java.lang on the JVM) is imported by default. Others such as kotlin.math, kotlin.time and java.util need an explicit import.
  2. 2. Two classes called Date from different packages are needed in one file. What is the idiomatic fix?

    Importing both fails with 'conflicting import'. An alias gives one (or both) a different local name, or you can use a fully qualified name for one.
  3. 3. Where must import lines appear in a Kotlin file?

    Imports are only allowed at the beginning of the file; the compiler reports 'imports are only allowed in the beginning of file' otherwise.
  4. 4. A file Shop.kt contains fun label(): String. What does a Java caller use on the JVM?

    Top-level members are compiled into a class named after the file with a Kt suffix. @file:JvmName can change the name.
  5. 5. Does Kotlin require the folder structure to match the package declaration?

    The compiler ignores the directory layout. Matching packages to folders is a convention that tools and teammates rely on.

Summary

  • A package line puts a file's declarations in a namespace; it is optional but expected in real projects, and the folder layout need not match (it should by convention).
  • import brings names into scope: classes, top-level functions and properties, object members and enum entries, or everything with *. Imports go at the top of the file.
  • Kotlin imports kotlin.*, kotlin.collections.*, kotlin.text.*, kotlin.io.* and a few more by default (plus java.lang.* on the JVM); everything else needs an import or a fully qualified name.
  • Resolve clashes with import ... as Alias, which renames a declaration only within the file.
  • Functions, properties and constants can live at the top level; on the JVM they compile into FileNameKt. Use private and internal to limit visibility, because there is no package-private level.
  • Organize by topic or feature, one main idea per file, and keep the public surface small.
  • In this tutorial's single-file runner, leave out the package line, or the main class will not be found.

Next: The Result Type