Part 05 / Topic 6 of 8
Local functions
A local function is a function declared inside another function. It's visible only inside the function that declares it, which is exactly the point: a small helper that only one place needs doesn't have to clutter the top level of the file.
fun validatedDiscount(amount: Double, percent: Double): String {
fun isValidPercent(p: Double) = p in 0.0..100.0
if (!isValidPercent(percent)) {
return "Invalid discount percent: $percent"
}
val discounted = amount - amount * percent / 100
return "₹%.2f".format(discounted)
}
fun main() {
println(validatedDiscount(1500.0, 20.0))
println(validatedDiscount(1500.0, 150.0))
}
₹1200.00
Invalid discount percent: 150.0
A local function can also read, and even change, a var that belongs to the function around it --
the same way an inner block can see an outer one:
fun billSummary(itemCount: Int): String {
var linesPrinted = 0
fun printLine(text: String) {
println(text)
linesPrinted++
}
printLine("Items: $itemCount")
printLine("Thank you for shopping")
return "Printed $linesPrinted lines"
}
Items: 3
Thank you for shopping
Printed 2 lines
printLine reaches out to linesPrinted, a variable declared in billSummary, not in
printLine itself -- and the final return sees every change printLine made to it. Reach for a
local function when a helper exists purely to serve one function's logic; once two or more
unrelated functions want the same helper, promote it to a top-level function instead (section 1).
Full program: examples/06_local_functions.kt.
Done here? The practice set for Part 5 — including the solutions — is on the part page.