Using Kotlin extension functions, we can make the definition and installation of our service's routes easier to read and maintain. To do this, perform the following steps:
- Start by creating a new package under the /src directory, and name that package routes:
- Now, we'll create a new file within this package named /src/routes/route_root.kt.
- Without route_root.kt, we will define an extension function on the Route type to define how our root endpoint route should be handled:
// route_root.kt
fun Route.root() {
get("/") {
call.respondText("Hello World", ContentType.Text.Plain)
}
}
You'll notice that we've simply moved our existing route definition out from Application.kt to the function body, Route.root(). Now, we can use this extension function to simplify the routing {} block within Application.module() as follows:
@kotlin.jvm.JvmOverloads
fun Application.module(testing: Boolean = false) {
HttpClient(Jetty) {
routing {
root()
}
}
}
Because the routing {} block has a receiver of the Route type, we can call our Route.root() extension function without explicitly referencing the receiver using this. Now, let's see how we can leverage this pattern to simplify the installation of additional routes.