In this tutorial, you’ll learn how to organize your code using packages in Kotlin.

Packages

In Java we use packages to group related classes; for example, the java.util package has a number of useful utility classes. Packages are declared with the package keyword, and any Kotlin file with a package declaration at the beginning can contain declarations of classes, functions, or interfaces.

Looking at the code below, we have declared a package com.kotlintutor.example using the package keyword. Also, we declared a class SampleClass inside this package.

package com.kotlintutor.example
class SampleClass

Now, the fully qualified name for the class SampleClass is com.kotlintutor.example.SampleClass.

package com.kotlintutor.example
fun sayHello(): String {
    return "Hello!"
}

In the code above, we created a top-level function. Similarly to ExampleClass, the fully qualified name for the function sayHello()is com.kotlintutor.example.sayHello.

In Kotlin, we use the import declaration to enable the compiler to locate the classes, functions, interfaces or objects to be imported. While in Java we can’t directly import functions or methods—only classes or interfaces.

We use import to access a function, interface, class or object outside the package where it was declared.

import com.kotlintutor.example.sayHello
fun main(args: Array<String>) {
    sayHello() // prints "Hello!"
}

In the code snippet above, we imported the function sayHello() from a different package and executed that function.

Kotlin also supports wildcard imports using the * operator. This will import all the classes, interfaces and functions declared in the package all at once. This is not recommended, though—it’s usually better to make your imports explicit.

import com.kotlintutor.example.*

When you have libraries that have conflicting class or function names (e.g. they each declare a function with the same name), you can use the as keyword to give that imported entity a temporary name.

import com.kotlintutor.example.sayHello
import com.kotlintutor.newExample.sayHello as newExampleSayHello
fun main(args: Array<String>) {
    newExampleSayHello()
}

Note that the temporary name is used only within the file where it was assigned.

Packages keep your code clean, organized, and reusable. It becomes easier to work with a lot of code.