Welcome to part 2 of the learning Kotlin series! If you haven’t yet, check out my first post that goes over getting started with Kotlin. In this post, we will be going over Lambda expressions and the syntax you can expect to see when using them. Let’s dive right in!
In case you are unfamiliar with lambda expressions, lambda expressions are a shorter way to define a function and its implementation. They are incredibly useful because you can store them in variables and execute them as regular functions. Because they can be defined as variables, you can also pass them as parameters to other functions or even be returned from a function.
You can define a lambda expression with the following syntax:
In this snippet, we are defining a variable called ‘multiplyLambda’ that is a lambda function. The function takes two parameters, x and y which are both integers. What’s interesting about this lambda is that the value from the last expression is implicitly returned. You can explicitly return a value using the qualified return syntax if you aren’t a fan of the auto return.
Kotlin’s type inference is very similar to c# here where the type is determined at compile time and therefore can be omitted from the declaration. In Kotlin, there are two types of inference that are supported.
- Local type inference: which is for locally defined statements.
- Function signature type inference: is what was talked about above where the inferred type of a function return value is calculated.
The example above is a simplified example of a lambda function. Here is a breakdown of all of the possible parts of one.
The important things to remember are:
- A lambda expression is always surrounded by curly braces.
- Parameter declarations (i.e. param1: Int) in the full syntax go inside of the curly braces and have those optional type annotations.
- The body is always after the → sign
- If the inferred return type of the lambda expression is not a Unit, the last expression inside the lambda body is treated as the return value (i.e example 1 the return is x*y)
Use that Lambda
As mentioned earlier, you can use lambda functions in a variety of ways. I know in c#, a common use case is using lambda expressions for event handling; i.e. button presses, event handlers, etc. According to this post, that is also a common use with Kotlin when making an app. For our example, once we define the lambda expression, using it is relatively easy.
If the lambda only has one parameter and the compiler can figure out the signature itself, then you are allowed to not declare the parameter and use ‘it’ instead. Let’s consider the following example:
The benefit of this type of syntax is that you can do something very similar to c# LINQ-style code:
I hope this breakdown helps you not be confused or intimidated by lambda functions going forward. At the end of the day they are just fancy functions.
If you have questions or comments, please comment below! Happy Coding!