Lambdas produce compact code that’s easier to understand.

A lambda (also called a function literal) is a low-ceremony function: it has no name, requires a minimal amount of code to create, and you can insert it directly into other code.

As a starting point, consider map(), which works with collections like List. map() takes its argument—a transformation function—and applies it to each element in a collection. It returns a new List containing all the transformed elements. Here, we transform each List item to a string surrounded with []:

// Lambdas/BasicLambda.kt import atomictest.eq fun main(args: Array<String>) { val list = listOf(1, 2, 3, 4) val result ={ n: Int -> "[$n]" }) result eq listOf("[1]","[2]","[3]","[4]") }

Here, the lambda is used in the initialization of result; it is the code within the curly braces. The argument list is separated from the function body by an arrow -> (the same arrow used in when expressions).

The function body can be one or more expressions. The final expression becomes the return value of the lambda.

End of sample. See for full early-access book.

Previous          Next

©2018 Mindview LLC. All Rights Reserved.