Functions Inside Functions

Kotlin allows you to define functions anywhere—even inside other functions.

Named functions defined within other functions are called local functions. Local functions reduce duplication by extracting repetitive code while restricting visibilty to the surrounding function. Here, even though log() is defined just like any other function, it’s nested inside main():

// LocalFunctions/LocalFunctions.kt fun main(args: Array<String>) { val logMsg = StringBuilder() fun log(message: String) = logMsg.appendln(message) log("Starting computation") // Imitating computation val x = 42 log("Computation result: $x") println(logMsg.toString()) } /* Output: Starting computation Computation result: 42 */

Local functions capture variables from the surrounding environment that would otherwise be passed as additional parameters. log() uses logMsg, which is defined in the outer function. This way, you don’t need to repeatedly pass logMsg into log().

End of sample. See for full early-access book.

Previous          Next

©2018 Mindview LLC. All Rights Reserved.