Lambda expressions

The simplest way to define anonymous functions in Kotlin is by using a feature called lambda expressions. They are similar to Java 8 lambda expressions, but the biggest difference is that Kotlin lambdas are actually closures, so they allow us to change variables from the creation context. This is not allowed in Java 8 lambdas. We will discuss this difference later in this section. Let's start with some simple examples. Lambda expressions in Kotlin have the following notation:

    { arguments -> function body } 

Instead of return, the result of the last expression is returned. Here are some simple lambda expression examples:

  • { 1 }: A lambda expression that takes no arguments and returns 1. Its type is ()->Int.
  • { s: String ...

Get Android Development with Kotlin now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.