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}")
}
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.139.80.209