Home > Software design >  How does defining functions within functions work?
How does defining functions within functions work?

Time:04-26

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?

CodePudding user response:

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 of the child function.

In case of type-safe builders, 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.

  • Related