Kotlin
package
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.
Exercise 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.
Show example solution
package com.example.app
fun greet(name: String): String = "Hello, $name!"
fun main() {
println(greet("Alex"))
}
Test yourself
-
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
- At the end of the file
Show answer
At the top of the file, before imports — package goes at the very top, before any imports.
-
Declare a package
____ com.example.app
Show answer
package com.example.app
-
Match the package concepts
- package
- Declares namespace
- com.example.app
- Package path
- file top
- Position
- reverse domain
- Naming convention
Next lesson: import