Labs ICT
โญ Pro Login

Lambda Functions

Lambdas are functions without a name โ€” you create them on the spot and pass them around like data. They're everywhere in Kotlin, especially when working with collections.

Lambda syntax

A lambda is wrapped in curly braces. The parameters go before ->, and the body goes after.


fun main() {
  val sum = { a: Int, b: Int -> a + b }
  println(sum(3, 4))
}
    

Here { a: Int, b: Int -> a + b } is a lambda that takes two integers and returns their sum. You can call it just like a regular function.

Try it Yourself โ†’

Passing lambdas to functions

Many Kotlin functions accept lambdas. forEach is a classic example.


fun main() {
  val numbers = listOf(1, 2, 3, 4, 5)
  numbers.forEach({ n -> println(n) })
}
    

When the lambda is the last argument, you can move it outside the parentheses.


fun main() {
  val numbers = listOf(1, 2, 3, 4, 5)
  numbers.forEach { n -> println(n) }
}
    
Try it Yourself โ†’

The it keyword

When a lambda has exactly one parameter, Kotlin lets you refer to it as it.


fun main() {
  val numbers = listOf(1, 2, 3, 4, 5)
  numbers.forEach { println(it) }
}
    

No need to name the parameter. it is the implicit name for a single parameter.

Try it Yourself โ†’

Lambdas with map and filter

This is where lambdas truly shine. Transform and filter collections with ease.


fun main() {
  val numbers = listOf(1, 2, 3, 4, 5, 6)
  val doubled = numbers.map { it * 2 }
  val evens = numbers.filter { it % 2 == 0 }
  println(doubled)
  println(evens)
}
    

map transforms each element. filter keeps only the elements that match the condition.

Try it Yourself โ†’

๐Ÿงช Quick Quiz

What is the lambda syntax in Kotlin?