Lambdas let you write small pieces of code that can be passed around and used like values. This helps you write programs by combining simple functions, which is the heart of functional style.
0
0
Why lambdas enable functional style in Kotlin
Introduction
When you want to quickly create a small function without naming it.
When you want to pass behavior as data to other functions, like sorting or filtering.
When you want to write clear and concise code that focuses on what to do, not how.
When you want to chain operations on collections in a readable way.
When you want to avoid changing variables and keep your code predictable.
Syntax
Kotlin
val lambdaName: (InputType) -> ReturnType = { parameter -> expression }Lambdas are anonymous functions you can store in variables or pass as arguments.
The arrow -> separates parameters from the function body.
Examples
This lambda takes an integer and returns its square.
Kotlin
val square: (Int) -> Int = { x -> x * x }
This lambda takes a name and returns a greeting message.
Kotlin
val greet: (String) -> String = { name -> "Hello, $name!" }
When there is one parameter, you can use
it instead of naming it.Kotlin
val isEven: (Int) -> Boolean = { it % 2 == 0 }
Sample Program
This program uses lambdas with filter and map to select even numbers and square all numbers in a list. It shows how lambdas help write clear, functional-style code.
Kotlin
fun main() { val numbers = listOf(1, 2, 3, 4, 5) val evenNumbers = numbers.filter { it % 2 == 0 } val squares = numbers.map { it * it } println("Even numbers: $evenNumbers") println("Squares: $squares") }
OutputSuccess
Important Notes
Lambdas make your code shorter and easier to read by removing the need for full function declarations.
Using lambdas encourages writing code without changing data, which helps avoid bugs.
Summary
Lambdas are small, unnamed functions you can use anywhere.
They let you pass behavior as data, which is key to functional programming.
Using lambdas helps write clear, concise, and predictable code.