Introducing Lambda Expressions

One thing that you will use a lot in Kotlin development is the lambda expression. It is particularly important when working with collections, as lambda expressions are critical for performing common operations, such as:

What is a Lambda Expression?

A simple way to start thinking about lambda expressions is to consider them just as a set of Kotlin statements wrapped in curly braces:

val lambda = { println("Hello, world!") }

However, as the val indicates, a lambda expression itself is an object. You can hold onto them in variables, pass them as function parameters, and do everything else that you might do with other types of objects.

Kotlin lambda expressions closely resemble their Java counterparts, along with similar constructs in other languages, such as Ruby blocks.

If you receive a lambda expression, and you want to run it, call invoke():

  val lambda = { println("Hello, world!") }

  lambda.invoke()

This prints “Hello, world!”, just as if you had just directly executed the println() call.

Where Do We Use Lambda Expressions?

At minimum, lambda expressions replace a lot of the “listener” or “callback” patterns that you might have used in Java. For example, rather than creating an implementation of a Comparator to support a sort() method, as we do in Java, you would use a lambda expression.

In particular, anything in Java where you might have used a listener or callback consisting of a class with a single method, a lambda expression will be the likely replacement.

Kotlin also lends itself towards the functional programming paradigm, where business logic is made up of linked function calls. We will explore that more when we look at immutability.

But, in a nutshell: you will use lambda expressions a lot in Kotlin.

Lambda Expressions, Parameters, and Return Values

Like functions, lambda expressions can take parameters:

  val squarifier = { x: Int -> x * x }

  println(squarifier.invoke(3))

Here, squarifier takes one parameter, named x, whose type is Int. The x: Int syntax is the same as function parameters. The list of parameters to a lambda expression come at the beginning, with the “body” of the lambda expression following the ->.

However, single-parameter lambdas are very common. For that, Kotlin offers a shorthand syntax: it. If the Kotlin compiler can determine the data type for the parameter, you can skip the parameter declaration and just refer to the parameter as it. We will see examples of this coming up shortly.

A lambda expression will return whatever its last statement does. In the case of squarifier, it has only one statement: x * x. So, that value is what the lambda expression returns from the call to invoke(). So, our REPL console output is 9, because the lambda expression takes 3 as input, squares it, and returns that squared value.


Prev Table of Contents Next

This book is licensed under the Creative Commons Attribution-ShareAlike 4.0 International license.