Package-level functions
-----------------------
Package-level functions are also known as top-level functions. They are declared directly inside a file without creating any class for them. They are often utility functions independent of any class:
**UserUtils.kt**
package com.app.user
fun getAllUsers() { }
fun getProfileFor(userId: String) { }
Usage:
import com.app.user.getProfileFor
val userProfile = getProfileFor("34")
You don't need to manually write the `import` statement, just type the function name and the auto-import will do its job.
----------
Package-level functions with a class
------------------------------------
When the functions are somewhat related to a class, define them just above the class, in the same file:
**User.kt**
package com.app.user
fun getAllUsers() { }
fun getProfileFor(userId: String) { }
data class User(val id: String, val name: String)
Usage:
import com.app.user.getAllUsers
val userList = getAllUsers()
----------
`companion object`
------------------
When the functions are closely related to a class, define them inside a `companion object`:
**User.kt**
data class User(val id: String, val name: String) {
companion object {
fun getAll() { }
fun profileFor(userId: String) { }
}
}
Usage:
import com.app.user.User
val userProfile = User.profileFor("34")
----------
That's it!