package
- Kotlin course
- Intermediate
- Lesson 100/116
- 4 min
Learn package declarations with package.
package: Namespace
A package declaration groups the definitions in a file into a namespace. The declaration goes at the very top of the file, before any imports. The namespace prevents clashes between classes and functions; it matters especially in large projects.
package com.example.app
class User(val name: String)Here the User class belongs to the com.example.app namespace; its fully qualified name is com.example.app.User. Without a declaration the default package is used; this is acceptable for small scripts but not recommended in projects. The namespace usually follows a reverse domain name convention.
The default package
If a file has no package declaration, its definitions go into the default package. This is acceptable for small trial scripts. In projects, however, using a package is a good habit; definitions in the default package risk clashing with definitions from other files.
// no package declaration
fun greet(name: String) = "Hello, $name!"The package usually follows a reverse domain name format such as com.company.product. This avoids clashes with internet domain names. Different modules in the same project can use different packages; this helps keep the code organized.
Practice Declare a package and greet
At the top of the file write package com.example.app. Define fun greet(name: String): String = "Hello, $name!". In main print greet("Alex") with println.
Starter code
// write the package declaration at the top: com.example.app
// greet function: returns Hello, {name}!
// main: print greet with println
fun main() {
// write here
}Sample solution
package com.example.app
fun greet(name: String): String = "Hello, $name!"
fun main() {
println(greet("Alex"))
}Expected output
Hello, Alex!
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Where does the package declaration go in a file?
- Inside the main function
- After the class definition
- At the top of the file, before imports Correct answer
- At the end of the file
Explanation: package goes at the very top, before any imports.
2 Declare a package
____ com.example.app
package com.example.app
Explanation: package com.example.app declares the namespace.
3 Match the package concepts
| Term | Meaning |
|---|---|
package |
Declares namespace |
com.example.app |
Package path |
file top |
Position |
reverse domain |
Naming convention |