Functions

Kotlin Lambda Expressions

Lambda Expressions

Kotlin lambda expressions use { } for concise function literals.

Introduction to Lambda Expressions

In Kotlin, lambda expressions are a simple way to create function literals. They allow you to write concise and flexible code by encapsulating a block of code that can be passed around as an argument or returned from a function. Lambda expressions in Kotlin are surrounded by curly braces { }.

Syntax of Lambda Expressions

A basic lambda expression in Kotlin is defined by the following syntax:

  • Parameters: Optional, declared before the arrow ->.
  • Arrow: Separates parameters from the body of the lambda.
  • Body: The code that is executed when the lambda is invoked.

Example of a simple lambda expression:

Using Lambdas with Higher-Order Functions

Lambdas are often used with higher-order functions, which are functions that take other functions as parameters or return them. The filter function is a common example:

Implicit 'it' Parameter

For lambdas with a single parameter, Kotlin has an implicit name it for the parameter, which can be used directly without explicit declaration.

Returning Values from Lambdas

In Kotlin, the last expression in a lambda is implicitly the return value. You don't need to use a return statement.

Conclusion

Kotlin lambda expressions are a powerful feature that allows for concise and readable code. By understanding how to define and use them, you can write more flexible and expressive functions. In the next post, we will explore higher-order functions, where lambdas play a crucial role.