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 -> println(s) }
: A lambda expression that takes one argument of typeString
, and prints it. It returnsUnit
. Its type is(String)->Unit
.{ a: Int, b: Int -> a + b }
: A lambda expression that takes twoInt
arguments and returns the sum of them...