Packages and imports
suggest changeEvery Kotlin source file belongs to a package. A package is a namespace: it groups related declarations and lets two libraries each have a Logger class without clashing. To use a declaration from another package you either write its fully qualified name or import it.
Kotlin's rules look like Java's at first, with a few important differences:
- a package can contain top-level functions, properties, objects and type aliases, not only classes
- you can import functions, properties, object members and enum entries, not only classes
import ... asrenames a declaration on import- the directory layout doesn't have to match the package name
- there is no
import static: a regularimportcovers it
Declaring a package
The package directive is the first statement in a file. Only file annotations (@file:...) and comments can come before it:
package com.example.geometry
import kotlin.math.PI
const val UNIT = "cm"
interface Shape {
fun area(): Double
}
class Circle(val radius: Double) : Shape {
override fun area() = PI * radius * radius
}
class Rect(val w: Double, val h: Double) : Shape {
override fun area() = w * h
}
fun describe(s: Shape): String =
"%s with area %.2f sq %s".format(s::class.simpleName, s.area(), UNIT)
val Shape.isLarge: Boolean get() = area() > 100.0
object Shapes {
fun unitSquare() = Rect(1.0, 1.0)
}
enum class Color { RED, GREEN, BLUE }
Everything declared in this file is in the package com.example.geometry. Its full name is the package name plus the declaration name: com.example.geometry.Circle, com.example.geometry.describe, com.example.geometry.UNIT.
Package names are by convention lowercase, without underscores, and start with a reversed domain you own (com.example, org.jetbrains, io.ktor).
Directory layout
On the JVM the compiled .class files always go into directories matching the package, but the source files don't have to. The compiler accepts Shapes.kt with package com.example.geometry in any directory.
The recommended layout still follows the package, but leaves out the common root. In a project where all code is under com.example, a file in com.example.geometry lives in src/main/kotlin/geometry/Shapes.kt. A layout identical to Java's (src/main/kotlin/com/example/geometry/Shapes.kt) works just as well, and is common in mixed Java/Kotlin projects.
Files without a package
A file with no package directive belongs to the default package, which has no name:
fun greet() = "no package"
fun main() {
println(greet())
}
no package
That is fine for scripts and small examples, like most in this book. In a real project avoid the default package. Files in other packages don't see its declarations unless they import them by their bare name (import greet), and Java code can't use them at all.
Importing declarations
Here is a file in another package that uses the geometry code:
package com.example.app
import com.example.geometry.Circle
import com.example.geometry.Rect
import com.example.geometry.describe
import com.example.geometry.isLarge
import com.example.geometry.UNIT
import com.example.geometry.Shapes
import com.example.geometry.Color.RED
fun main() {
val shapes = listOf(Circle(2.0), Rect(20.0, 10.0), Shapes.unitSquare())
for (s in shapes) {
println("${describe(s)}, large: ${s.isLarge}")
}
println("unit: $UNIT, color: $RED")
}
Compile both files and run the main function. A top-level main in file Main.kt ends up in class MainKt of the file's package:
$ kotlinc src -d out
$ kotlin -cp out com.example.app.MainKt
Circle with area 12.57 sq cm, large: false
Rect with area 200.00 sq cm, large: true
Rect with area 1.00 sq cm, large: false
unit: cm, color: RED
The example shows the kinds of things you can import:
| Import | What it brings in |
|---|---|
import com.example.geometry.Circle |
a class |
import com.example.geometry.describe |
a top-level function |
import com.example.geometry.UNIT |
a top-level property or constant |
import com.example.geometry.isLarge |
an extension property (same for extension functions) |
import com.example.geometry.Shapes |
an object |
import com.example.geometry.Color.RED |
an enum entry |
Note that Shape is not imported. The code never names the type, so it doesn't need to: an import is only about which names you can write unqualified.
Extensions are the one case where you really must import: an extension function or property declared in another package isn't visible on the receiver until it is imported. See Top-Level Extensions.
Where imports go
Imports come after the package directive and before any other declaration. An import further down is a syntax error:
object Config { val name = "app" }
import Config.*
b.kt:1:35: error: syntax error: imports are only allowed in the beginning of file.
Importing a name that doesn't exist is a compile error:
import kotlin.math.squareRoot
fun main() {}
bad.kt:1:20: error: unresolved reference 'squareRoot'.
import kotlin.math.squareRoot
^^^^^^^^^^
Unused imports, on the other hand, are not reported by the compiler. IntelliJ IDEA and Android Studio grey them out and remove them with Optimize Imports (Ctrl+Alt+O).
Fully qualified names
You don't have to import anything. A fully qualified name works anywhere a type or function name is expected:
fun main() {
val id = java.util.UUID.nameUUIDFromBytes("kotlin".toByteArray())
println(id)
println(kotlin.math.sqrt(2.0))
}
4fba3bc0-2b72-3e9a-a87a-1e5286e373c6
1.4142135623730951
This is handy when a name is used only once, or to make clear which of two same-named types you mean.
Star imports
import package.* imports every accessible declaration of a package:
import kotlin.math.*
fun main() {
println(sqrt(16.0) + max(2, 3) + abs(-1))
println(PI)
}
8.0
3.141592653589793
A star import also works on a class, to import its nested classes and, for an enum, its entries:
package app
import app.Level.*
import app.Outer.Nested
import app.Temperature.Companion.fromFahrenheit
enum class Level { LOW, MEDIUM, HIGH }
class Outer {
class Nested { override fun toString() = "Nested" }
}
class Temperature(val celsius: Double) {
companion object {
fun fromFahrenheit(f: Double) = Temperature((f - 32) * 5 / 9)
}
}
fun main() {
println(listOf(LOW, HIGH))
println(Nested())
println(fromFahrenheit(212.0).celsius)
}
[LOW, HIGH]
Nested
100.0
You can import an individual member of an object or a companion object, as fromFahrenheit above shows, but you can't star-import from an object:
package demo
import demo.Config.*
object Config { val name = "app" }
c.kt:3:13: error: cannot import on demand from object 'Config'.
import demo.Config.*
^^^^^^
Import the members by name instead:
package demo
import demo.Config.greet
import demo.Config.name
object Config {
val name = "app"
fun greet() = "hi from $name"
}
fun main() {
println(name)
println(greet())
}
app
hi from app
The official Kotlin style guide allows star imports freely. IntelliJ IDEA's default setting switches to a star import when you use 5 or more names from one package, and always uses star imports for java.util, kotlinx.android.synthetic and io.ktor. Many teams turn that off so every import is explicit.
Renaming imports with as
import ... as NewName brings in a declaration under a different name. The main use is resolving conflicts between two declarations with the same name:
import java.util.Date
import java.sql.Date as SqlDate
import java.time.LocalDate as Day
fun main() {
val now = Date(0)
val sqlDay = SqlDate.valueOf("2026-10-17")
println(now.time)
println(sqlDay)
println(Day.of(2026, 1, 31).plusDays(1))
}
0
2026-10-17
2026-02-01
The alias is local to the file. It doesn't change the declaration and other files don't see it. When you import something under an alias, the original name is not available in that file: LocalDate would be an unresolved reference above.
Aliases work for functions and extensions too:
package app
import com.example.text.slugify as toSlug
import kotlin.text.isBlank as blank
fun main() {
println(toSlug("Hello, World"))
println(" ".blank())
}
hello-world
true
To share a short name across the whole project, use a type alias instead: typealias SqlDate = java.sql.Date declared once can be imported like any other declaration.
Importing Java static members
Kotlin has no import static. A regular import works for static methods and fields of Java classes:
import java.lang.Integer.MAX_VALUE
import java.lang.Math.floorMod
fun main() {
println(floorMod(-7, 3))
println(MAX_VALUE)
}
2
2147483647
Default imports
Some packages are imported into every Kotlin file automatically, which is why println, listOf, Regex and File.readText work without imports:
kotlin.*kotlin.annotation.*kotlin.collections.*kotlin.comparisons.*kotlin.io.*kotlin.ranges.*kotlin.sequences.*kotlin.text.*
On the JVM also:
java.lang.*kotlin.jvm.*
Notably not included: kotlin.math, kotlin.random, kotlin.time, kotlin.concurrent, java.util, java.io and kotlinx.coroutines. Those need explicit imports.
How names are resolved
When the same name is reachable in more than one way, Kotlin picks in this order (highest priority first):
- explicit imports (
import one.hello) and aliases - declarations in the same package as the current file
- star imports (
import one.*) - default imports
Given two packages that each declare hello() and a Logger class:
package one
fun hello() = "one.hello"
class Logger { override fun toString() = "one.Logger" }
package two
fun hello() = "two.hello"
class Logger { override fun toString() = "two.Logger" }
Star-importing both makes hello() ambiguous:
package app
import one.*
import two.*
fun main() {
println(hello())
}
amb.kt:7:13: error: overload resolution ambiguity between candidates:
fun hello(): String
fun hello(): String
An explicit import outranks star imports, and aliases let you use both classes:
package app
import one.*
import two.*
import two.hello
import one.Logger as OneLogger
import two.Logger as TwoLogger
fun main() {
println(hello())
println(OneLogger())
println(TwoLogger())
}
two.hello
one.Logger
two.Logger
A declaration in the current package beats a star import, but loses to an explicit import:
package app
import one.*
fun hello() = "app.hello"
fun main() {
println(hello()) // app.hello; with `import one.hello` it would be one.hello
}
app.hello
Because default imports have the lowest priority, your own declarations silently shadow standard library ones. This is legal, but confusing to readers:
package app
data class Pair(val left: String, val right: String)
fun println(message: Any?) = kotlin.io.println(">> $message")
fun main() {
println(Pair("a", "b")) // app.Pair and app.println
println(kotlin.Pair(1, 2)) // fully qualified to get the standard one
println("hello" to "world") // `to` still returns kotlin.Pair
}
>> Pair(left=a, right=b)
>> (1, 2)
>> (hello, world)
Visibility and packages
Packages interact with visibility modifiers:
public(the default) top-level declarations can be imported from anywhereprivatetop-level declarations are visible only inside the file, not the whole packageinternaldeclarations are visible in the same module (a Gradle source set, a Maven project, onekotlincinvocation), regardless of packageprotectedis not allowed on top-level declarations
Kotlin has no Java-style "package-private" visibility. Files in the same package see each other's public and internal declarations, but not private ones:
package com.example.text
fun slugify(s: String): String =
s.lowercase().replace(Regex("[^a-z0-9]+"), "-").trim('-')
private fun helper() = "only visible in this file"
internal fun moduleOnly() = "visible in this module"
package com.example.text
fun main() {
println(helper())
}
other.kt:4:13: error: cannot access 'fun helper(): String': it is private in file.
Top-level declarations on the JVM
The JVM has no top-level functions, so the compiler puts the top-level functions and properties of each file into a class named after the file: Shapes.kt in com.example.geometry produces com.example.geometry.ShapesKt, next to Circle.class, Rect.class and the others.
From Kotlin you never see that class; you import com.example.geometry.describe directly. From Java you call ShapesKt.describe(...). The @file:JvmName annotation, placed before package, gives the class a nicer name:
@file:JvmName("StringUtils")
package com.example.text
fun slugify(s: String): String =
s.lowercase().replace(Regex("[^a-z0-9]+"), "-").trim('-')
import com.example.text.StringUtils;
public class Main {
public static void main(String[] args) {
System.out.println(StringUtils.slugify("Packages and Imports in Kotlin!"));
}
}
packages-and-imports-in-kotlin
The name also matters when running a program: a main in Main.kt of package com.example.app is started with kotlin -cp out com.example.app.MainKt, or with Main-Class: com.example.app.MainKt in a jar manifest. See Compile and Run Kotlin Code in Command Line.
Summary
package a.b.cat the top of a file sets the namespace of everything in it; the source directory doesn't have to match.import a.b.Nameimports a class, function, property, object, object member or enum entry;import a.b.*imports everything from a package, class or enum (but not from an object).import a.b.Name as Otherrenames on import, which resolves name clashes.- Explicit imports beat same-package declarations, which beat star imports, which beat default imports.
kotlin.*,kotlin.collections.*,kotlin.text.*,kotlin.io.*and a few more (plusjava.lang.*on the JVM) are imported automatically;kotlin.mathandjava.utilare not.privatetop-level means private to the file; there is no package-private.- Top-level functions in
File.ktcompile to classFileKt; rename it with@file:JvmName.