赞
踩
本文翻译自官方权威文档Packages and Imports
内容中额外增加个人补充的知识点和实例。
如有纰漏或者错误,欢迎指正!
一个源文件可以以一个包声明作为开头:
package foo.bar //包名
fun baz() {}
class Goo {}
// ...
源文件的所有内容(例如类和方法)都被包含在声明的包中。所以,在上面的例子中,baz()方法全名是foo.bar.baz,以及Goo的全名是foo.bar.Goo
如果包没有被指定,该文件的内容都属于默认包,该默认包没有姓名。
每个Kotlin文件默认引用的一组包如下:
额外的包的引用依赖于目标平台:
JVM:
JS:
除了默认的引用,每个文件可以包含各自独立的引用指令。导入的语法在语法中描述。
我们可以导入一个单独包名, 例如:
import foo.Bar // Bar可以访问
或者可以访问一定范围的内容(包,类,对象等等):
import foo.* // 在'foo'中的所有东西都可访问
如果有名称冲突,我们可以通过使用关键字来消除歧义,在本地重命名冲突的实体。
import foo.Bar // Bar可访问
import bar.Bar as bBar // bBar来代表'bar.Bar'
import
关键字不仅限于导入类;你也可以使用import来导入其他的声明:
不像Java,Kotlin没有分离的import static
语法;所有的这些声明都通过使用一般的import
关键字来导入。
JDK1.5中新增的特性:import static-静态导入。加上static表示直接导入这个类中的静态方法(也可以指定具体某个静态方法)。导入后,可以在该类直接用method()方法名调用静态方法,而不需要ClassName.method()的方式来调用。
如果顶层声明使用private
标记,那么它对于所声明的文件就是私有的(参考:见可见性修饰符)
官方文档原文如下:
A source file may start with a package declaration:
package foo.bar
fun baz() {}
class Goo {}
// ...
All the contents (such as classes and functions) of the source file are contained by the package declared. So, in the example above, the full name of baz() is foo.bar.baz, and the full name of Goo is foo.bar.Goo.
If the package is not specified, the contents of such a file belong to “default” package that has no name.
A number of packages are imported into every Kotlin file by default:
Additional packages are imported depending on the target platform:
JVM:
JS:
Apart from the default imports, each file may contain its own import directives. Syntax for imports is described in the grammar.
We can import either a single name, e.g.
import foo.Bar // Bar is now accessible without qualification
or all the accessible contents of a scope (package, class, object etc):
import foo.* // everything in 'foo' becomes accessible
If there is a name clash, we can disambiguate by using as keyword to locally rename the clashing entity:
import foo.Bar // Bar is accessible
import bar.Bar as bBar // bBar stands for 'bar.Bar'
The import
keyword is not restricted to importing classes; you can also use it to import other declarations:
Unlike Java, Kotlin does not have a separate "import static"
syntax; all of these declarations are imported using the regular import
keyword.
If a top-level declaration is marked private
, it is private to the file it’s declared in (see Visibility Modifiers).
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。