Local Functions
In this page:
Declaring a Local Function
A function defined inside another function's body is a local function, usable only within that enclosing function, which keeps small helpers scoped tightly to where they are needed.
Example: Declaring a Local Function
fun printReport(total: Int) {
fun formatCurrency(amount: Int): String = "$$amount.00"
println("Total: ${formatCurrency(total)}")
}
fun main() {
printReport(150)
}
Login to try C/C++/Java/PHP code in the editor
Accessing Enclosing Variables
A local function can read variables from the function it is nested inside directly, without needing them passed in as parameters.
Example: Accessing Enclosing Variables
fun calculateDiscountedTotal(prices: List<Int>, discountPercent: Int) {
fun applyDiscount(price: Int): Int = price - (price * discountPercent / 100)
val total = prices.sumBy { applyDiscount(it) }
println("Discounted total: $total")
}
fun main() {
calculateDiscountedTotal(listOf(100, 200, 300), 10)
}
Login to try C/C++/Java/PHP code in the editor
Breaking Up Long Functions
Extracting repeated or logically distinct steps into local functions keeps the outer function's body focused on the overall flow, while the details live in named, testable-in-isolation pieces.
Example: Breaking Up Long Functions
fun processOrder(itemCount: Int, pricePerItem: Int) {
fun subtotal() = itemCount * pricePerItem
fun tax(amount: Int) = amount / 10
val sub = subtotal()
println("Subtotal: $sub, Tax: ${tax(sub)}")
}
fun main() {
processOrder(3, 50)
}
Login to try C/C++/Java/PHP code in the editor
When to Avoid Local Functions
If a helper needs to be reused across several unrelated functions, it should be a regular top-level (or member) function instead of a local one, since local functions cannot be called from outside their enclosing function.
Example: When to Avoid Local Functions
fun square(x: Int) = x * x
fun sumOfSquares(a: Int, b: Int): Int {
return square(a) + square(b)
}
fun main() {
println("Sum of squares: ${sumOfSquares(3, 4)}")
}
Login to try C/C++/Java/PHP code in the editor
- Making a helper a top-level function when it is only ever needed inside one other function, cluttering the file's namespace.
- Forgetting that a local function can directly access the variables of its enclosing function, leading to redundant parameters being passed in.
- Nesting local functions too deeply, hurting readability instead of helping it.
- A local function is declared inside another function's body and is only visible there.
- Local functions can directly read (and, if
var, modify) variables from their enclosing function's scope. - They help break a long function into smaller named pieces without polluting the outer file scope.
- Overusing deeply nested local functions can hurt readability just as much as one giant function.
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: