Andrew Wood
Andrew Wood

Reputation: 11

How does defining functions within functions work?

I am trying to get to know Kotlin through making a Ktor program, and was following the documentation when I noticed this:

fun Application.configureRouting() {

    routing {
        get("/") {
            call.respondText("Hello World!")
        }
    }
}

How does the routing {} and get("/") {} work? What does it mean? Is routing and get a function being overridden within the Application.configureRouting() function?

Upvotes: 0

Views: 175

Answers (1)

YektaDev
YektaDev

Reputation: 540

I suppose you confused Kotlin's type-safe builders with local functions. It's possible to define a function inside another function (local function) which limits the scope in which we can access the child function.

Here's an example of a local function:

fun foo() {
    fun bar() {
        println("I'm within a local function.")
    }

    println("We can call bar only from foo.")
    bar()
}

In case of type-safe builders (the routing function of your code), a part of the syntax that enabled this look and feel, is:

According to Kotlin convention, if the last parameter of a function is a function, then a lambda expression passed as the corresponding argument can be placed outside the parentheses.

When the only parameter of a function is of a lambda type, the parentheses can be omitted. Also, adding a receiver to a single lambda parameter will result in a behavior similar to the routing function that you mentioned. If my explanation is not sufficient, you can read more about type-safe builders from the official docs.

Upvotes: 2

Related Questions