import
- Kotlin course
- Intermediate
- Lesson 101/116
- 4 min
Learn to import packages with import.
import: Bringing in
An import declaration makes a class or function from another namespace available in the file. The declaration goes after package and before any definitions. The imported type can be used by its simple name.
package com.example.app
import java.io.File
fun main() {
val f = File("record.txt")
}Here java.io.File is imported; now it can be written short as File. It is also possible to write the fully qualified name: java.io.File("record.txt"). But this is long and hard to read; import is preferred.
Wildcard import
To import all types in a namespace, write import package.*. This is called a wildcard import. It is practical when many types are needed; however it can increase the risk of name clashes.
import java.io.* // File, BufferedReader, InputStream etc.
import kotlinx.coroutines.flow.*Wildcards shorten the code but can make it unclear which type comes from where. IDEs usually suggest single imports; this is clearer and more traceable. If two types with the same simple name are imported from different namespaces, one must be imported with an alias.
Practice Import File and use it
At the top write package com.example.app. Then add the line import java.io.File. In main create a File with val f = File("kayit.txt") and print it with println(f) (File toString returns the path).
Starter code
// package: com.example.app
// import the java.io.File class
// main: create a File object (path kayit.txt) and println
fun main() {
// write here
}Sample solution
package com.example.app
import java.io.File
fun main() {
val f = File("kayit.txt")
println(f)
}Expected output
kayit.txt
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Import a class
____ java.io.File
import java.io.File
Explanation: import java.io.File brings the class in.
2 Match the import concepts
| Term | Meaning |
|---|---|
import java.io.File |
Single type |
import kotlinx.* |
Wildcard |
simple name |
Short name |
fully qualified |
Full path |
3 What does import java.io.File do?
- Defines a new File class
- Renames the package
- Creates a File instance
- Makes File usable by its simple name Correct answer
Explanation: import makes File usable by its simple name.