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 args

Single-Expression Functions

fun square(n: Int) = n * n
fun isAdult(age: Int) = age >= 18

Lambdas 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 lambda

Extension Functions

fun String.slug(): String =
    lowercase().replace(Regex("[^a-z0-9]+"), "-")
"Hello World!".slug()  // hello-world

Add 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.

Lambda pipeline filter map sum plus extension functions

Key Points

  • Defaults plus named args kill most overloads.
  • Trailing lambdas make DSLs and retries beautiful.
  • Extensions add power without subclassing.
Share this post:

Comments (0)

Please login or register to comment.

Create a free account to keep reading

You've enjoyed a free tutorial! Register (it's free) to unlock every tutorial, track your progress and save code.

or sign in with your account

Already have an account? Log in