Functions, Lambdas and Extension Functions
Harry
· 23 Sep 2026
· 3 views
Log in to track your progress and mark lessons complete.
Function Basics
fun discount(price: Int, pct: Int = 10): Int {
return price - price * pct / 100
}
discount(500) // default arg
discount(price = 500, pct = 20) // named argsSingle-Expression Functions
fun square(n: Int) = n * n
fun isAdult(age: Int) = age >= 18Lambdas and Higher-Order Functions
val nums = listOf(1, 2, 3, 4)
nums.filter { it % 2 == 0 }.map { it * 10 } // [20, 40]
fun retry(times: Int, block: () -> Unit) {
repeat(times) { block() }
}
retry(3) { println("trying") } // trailing lambdaExtension Functions
fun String.slug(): String =
lowercase().replace(Regex("[^a-z0-9]+"), "-")
"Hello World!".slug() // hello-worldAdd behaviour to any class - even JDK and library classes - without inheritance.
Scope Functions at a Glance
- let - transform nullable values.
- apply - configure an object, return it.
- also - side effects (logging) in chains.
- run/with - compute with an object in scope.
- Defaults plus named args kill most overloads.
- Trailing lambdas make DSLs and retries beautiful.
- Extensions add power without subclassing.