Kotlin Packages and Imports
Packages
The package keyword defines a package, and the package declaration is placed at the top of the source code.
package com.devkuma
fun foo() {}
class Item {}
// ...
All contents of the source file, such as classes and functions, are included in the declared package. Therefore, as shown in the example above, the fully qualified name of foo() is com.devkuma.foo, and the fully qualified name of Item is com.devkuma.Item.
If no package is specified, the contents of the file belong to the unnamed “default” package.
Default Packages
The following eight packages are imported by default. Therefore, they can be used without separate imports.
* means “all.”
kotlin.*
kotlin.annotation.*
kotlin.collections.*
kotlin.comparisons.*
kotlin.io.*
kotlin.ranges.*
kotlin.sequences.*
kotlin.text.*
Additional packages are imported depending on the platform.
JVM:
java.lang.*
kotlin.jvm.*
JS:
kotlin.js.*
Imports
import brings in a package. as assigns an alias to an imported entity.
Except for the default imports, some files have their own import directives.
You can import only a single name.
import foo.Bar // Bar becomes accessible.
Or you can make everything in a scope, such as a package, class, or object, accessible.
import foo.* // Everything in 'foo' becomes accessible.
If there is a name conflict, you can use the as keyword to locally rename the conflicting entity and make it clear.
import foo.Bar // Bar is accessible.
import bar.Bar as bBar // bBar means 'bar.Bar'.
The import keyword is not limited to importing classes. It can also be used to import other declarations.
- Top-level functions and properties
- Functions and properties declared in object declarations
- Enum constants
Unlike Java, Kotlin does not provide a separate “import static” syntax. All declarations are imported only with the import keyword.
Visibility of Top-Level Declarations
If a top-level declaration is marked private, it is private to the source file in which it is declared.