74 lines
2.3 KiB
Plaintext
74 lines
2.3 KiB
Plaintext
_Packages_ are containers for [classes|Classes and Inheritance], [objects|Object expressions and Declarations], [functions|Functions] and [properties|Properties And Fields]. A Kotlin package is _something like_ a package in *Java*, but it is not tied up to any physical file-system entity.
|
|
|
|
h3. Root package
|
|
|
|
Every [module|Modules and Compilation] declares a unique _root package_, that contains all the packages declared in this module.
|
|
|
|
h3. Header package declaration
|
|
|
|
A source file may start with a _header package declaration_ (see [the grammar|Grammar#packageHeader]):
|
|
{jet}
|
|
package foo.bar
|
|
|
|
// ...
|
|
{jet}
|
|
|
|
All the contents of the source file are (directly or indirectly) contained by its header package. If the header is not specified, the module's root package is used.
|
|
|
|
h3. Imports
|
|
|
|
Besides the [default imports|Modules and Compilation#Default imports] declared by the module, each file may contain its own import directives.
|
|
|
|
Syntax for imports is described [here|Grammar#import].
|
|
|
|
One can import either a single name, e.g.
|
|
{jet}
|
|
import foo.Bar // Bar is now accessible withou qualification
|
|
{jet}
|
|
or all the accessible contents of a scope (package, class, object etc):
|
|
{jet}
|
|
import foo.* // everything in 'foo' becomes accessible
|
|
{jet}
|
|
If there is a name clash, one can disambiguate by using {{as}} keyword to locally rename the clashing entity:
|
|
{jet}
|
|
import foo.Bar // Bar is accessible
|
|
import bar.Bar as bBar // bBar stands for 'bar.Bar'
|
|
{jet}
|
|
|
|
h3. Absolute and relative names
|
|
|
|
Consider the following example (syntax is fictional):
|
|
{jet}
|
|
package a {
|
|
package b {
|
|
val x = 1
|
|
package a {
|
|
val y = a.b.x // Problem
|
|
}
|
|
}
|
|
}
|
|
{jet}
|
|
At the line marked "Problem" we have the following potential ambiguity: what does {{a}} stand for: the outer *package* {{a}} or the inner one? The rule here is that names are always _relative_: {{a}} is resolved in its scope of occurrence that makes it mean the inner *package* {{a}}, so this code does not compile.
|
|
|
|
To fix it, we need an _absolute_ name. These start with the *package* keyword:
|
|
|
|
{jet}
|
|
package a {
|
|
package b {
|
|
val x = 1
|
|
package a {
|
|
val y = package.root.a.b.x // Fixed
|
|
}
|
|
}
|
|
}
|
|
{jet}
|
|
In this example, we assumed that the root package of our module is named {{root}}.
|
|
|
|
Absolute names may be used in imports as well:
|
|
{jet}
|
|
import package.root.a.b.a.*
|
|
{jet}
|
|
|
|
h3. What's next
|
|
|
|
* [Functions] |