官术网_书友最值得收藏!

The import keyword

Often, classes and types need to make use of other classes and types existing outside the package in which they are declared. This can be done by importing package resources. If two classes belong in the same package, no import is necessary:

package animals
data class Buffalo(val mass: Int, val maxSpeed: Int, var isDead: Boolean = false)

In the following code snippet, the Buffalo class does not need to be imported into the program because it exists in the same package (animals) as the Lion class:

package animals
class Lion(val mass: Int, val maxSpeed: Int) {

fun kill(animal: Buffalo) { // Buffalo type used with our import
if (!animal.isDead) {
println("Lion attacking animal.")
animal.isDead = true
println("Lion kill successful.")
}
}
}

In order to import classes, functions, interfaces, and types in separate packages, we use the import keyword followed by the package name. For example, the following main function exists in the default package. As such, if we want to make use of the Lion and Buffalo classes in the main function, we must import it with the import keyword. Consider the following code:

import animals.Buffalo
import animals.Lion

fun main(args: Array<String>) {
val lion = Lion(190, 80)
val buffalo = Buffalo(620, 60)
println("Buffalo is dead: ${buffalo.isDead}")
lion.kill(buffalo)
println("Buffalo is dead: ${buffalo.isDead}")
}
主站蜘蛛池模板: 东台市| 鄢陵县| 合阳县| 潢川县| 剑川县| 稷山县| 神池县| 牟定县| 惠水县| 南川市| 衡阳市| 蓬莱市| 鹿邑县| 民县| 莲花县| 齐齐哈尔市| 衡东县| 五河县| 连江县| 闽侯县| 永济市| 科技| 凯里市| 蒲江县| 信丰县| 石楼县| 新津县| 奎屯市| 东平县| 班戈县| 开封市| 金川县| 武平县| 衡南县| 波密县| 宁波市| 凤凰县| 香港| 湘潭市| 丹凤县| 克什克腾旗|