The Importance of Lambdas

Lambdas can seem like syntactic sugar, but they provide important power to your programming.

Code often manipulates the contents of a collection, and typically repeats these manipulations with minor modifications. Consider selecting elements from a collection, such as people under a given age, employees with a specific role, citizens of a particular city, or unfinished orders. Here’s an example that selects even numbers from a list. Suppose we don’t have a rich library of functions for working with collections—we’d have to implement our own filterEven() operation:

// ImportanceOfLambdas/FilterEven.kt import atomictest.eq fun filterEven(nums: List<Int>): List<Int> { val result = mutableListOf<Int>() for (i in nums) if (i % 2 == 0) // [1] result += i return result } fun main(args: Array<String>) { filterEven(listOf(1, 2, 3, 4)) eq listOf(2, 4) }

If an element has a remainder of 0 when divided by 2, it’s appended to the result.

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



Previous          Next

©2018 Mindview LLC. All Rights Reserved.