Application
- Kotlin course
- Advanced
- Lesson 21/83
- 5 min
Learn Application and module structure.
What is Application?
Application is the central point of a Ktor server. Plugins, routing and lifecycle are attached here. It is configured through an Application.module() function.
Example: fun Application.module() { install(ContentNegotiation); routing { ... } }. This function is referenced by module name in the embeddedServer call. module is a common name; any name works. You can define several modules and connect them in sequence. This structure breaks the server configuration into pieces.
Binding a module
You bind a module in the embeddedServer call. Example: embeddedServer(Netty, port = 8080, module = Application::module).
Here the module parameter takes a reference to the module function. The default module name is module; if it differs you must specify it. Modules are used to split the server: authentication in one module, reporting in another. This separation improves readability.
Practice Define Application.module
Define fun Application.module(). Inside main, print println("Module ready").
Starter code
// Application
// write here
import io.ktor.server.application.*
fun main() {
}Sample solution
fun Application.module() {
}
fun main() {
println("Module ready")
}Expected output
Module ready
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Match Application parts
| Term | Meaning |
|---|---|
Application |
Central point |
module() |
Configuration |
install |
Adds plugin |
routing |
Route definition |
2 What does Application.module() do?
- Holds configuration Correct answer
- Picks engine
- Starts the server
- Makes HTTP request
Explanation: module() holds plugin and routing configuration.
3 Complete the Application.module definition
fun ____.module() {
install(ContentNegotiation)
}
fun Application.module() {
install(ContentNegotiation)
}
Explanation: fun Application.module() is the definition.