Kotlin

Local Functions

admin by @admin ADMIN
1h ago
Jun 1, 2026
Public
0 0 up · 0 down Sign in to vote
Functions can be declared inside other functions. Closures over outer scope let you eliminate parameter-threading. Use sparingly — too many nested locals hurts readability.
Kotlin
Raw
fun processUsers(users: List<String>): Map<String, Int> {
    val result = mutableMapOf<String, Int>()

    // Local function — captures `result` from outer scope
    fun record(name: String, score: Int) {
        result[name] = (result[name] ?: 0) + score
    }

    users.forEach { user ->
        when {
            user.startsWith("admin_") -> record(user, 100)
            user.length > 8           -> record(user, 50)
            else                      -> record(user, 10)
        }
    }
    return result
}

fun main() {
    val scores = processUsers(listOf("admin_root", "alice", "verylongname", "bob"))
    println(scores)
}
Tags

Save your own code snippets

Create a free account and build your private vault. Share publicly whenever you want.