O'Reilly logo

Android Development with Kotlin by Igor Wojda, Marcin Moskala

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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, 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 -> println(s) ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required