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! 💡
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.
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.
A basic Kotlin Lambda Expression looks like this:
(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.Let's create a simple Lambda Expression that squares a number:
val square: (Int) -> Int = { number -> number * number }
println(square(4)) // Output: 16In 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.
Now, let's see how we can use Lambda Expressions with Higher-Order Functions like map, filter, and sortBy.
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.
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! 🚀