Kotlin Lambda Expressions 🎯

beginner
6 min

Kotlin Lambda Expressions 🎯

Welcome back, coding enthusiasts! Today, we're diving into the world of Kotlin Lambda Expressions. This powerful feature will help you write cleaner, more efficient code! 💡

What are Lambda Expressions? 📝

In simple terms, Lambda Expressions are anonymous functions that can be used wherever a Function Type is required. They don't have a name, but they can still perform a specific task.

Why Lambda Expressions? ✅

Lambda Expressions provide a concise syntax to implement small, one-off functionalities without the need to define separate function bodies. This makes our code more readable, less cluttered, and easier to maintain.

Understanding Kotlin Lambda Syntax 📝

A basic Kotlin Lambda Expression looks like this:

kotlin
(parameters) -> (return type) { (function body) }

Let's break it down:

  • (parameters): The parameters the function accepts.
  • ->: The arrow separates the function parameters from the return type and the function body.
  • (return type): The return type of the function. It's optional if Kotlin can infer it from the context.
  • { (function body) }: The function body, containing the code to be executed.

Example 1: Simple Lambda Expression 💡

Let's create a simple Lambda Expression that squares a number:

kotlin
val square: (Int) -> Int = { number -> number * number } println(square(4)) // Output: 16

In this example, square is a Lambda Expression that takes an Int and returns an Int. The function body number * number calculates the square of the input number.

Example 2: Lambda Expressions with Higher-Order Functions 💡

Now, let's see how we can use Lambda Expressions with Higher-Order Functions like map, filter, and sortBy.

kotlin
val numbers = listOf(1, 4, 3, 5, 2) val squaredNumbers = numbers.map { it * it } println(squaredNumbers) // Output: [1, 16, 9, 25, 4]

In this example, we're using the map Higher-Order Function to apply the square operation to each element in the numbers list.

Quiz Time! 🎯

Quick Quiz
Question 1 of 1

What does a Kotlin Lambda Expression do?

Stay tuned for more advanced Kotlin Lambda Expressions and real-world examples in our next lesson! Happy coding! 🚀