- Kotlin Programming By Example
- Iyanu Adelekan
- 217字
- 2021-08-27 20:00:12
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}")
}
- Learn to Create WordPress Themes by Building 5 Projects
- arc42 by Example
- Web全棧工程師的自我修養
- Expert Data Visualization
- MySQL入門很輕松(微課超值版)
- 軟件供應鏈安全:源代碼缺陷實例剖析
- Mastering Adobe Captivate 7
- Natural Language Processing with Python Quick Start Guide
- HTML+CSS+JavaScript網頁制作:從入門到精通(第4版)
- Appcelerator Titanium:Patterns and Best Practices
- TypeScript圖形渲染實戰:2D架構設計與實現
- 3D Printing Designs:The Sun Puzzle
- 每個人的Python:數學、算法和游戲編程訓練營
- H5頁面設計與制作(全彩慕課版·第2版)
- Instant Buildroot