In this tutorial, you’ll learn how to organize your code using packages in Kotlin.
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.
Now, the fully qualified name for the class
In the code above, we created a top-level function. Similarly to
ExampleClass, the fully qualified name for the function
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.
import to access a function, interface, class or object outside the package where it was declared.
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.
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.
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.