Learning Kotlin: Collections

Note *

The Koans for Kotlin are broken into sections, and our earlier posts have covered the first section; this post is going to cover the entire second section. The reason we are not breaking this down as we did before is because the common theme here is working with the kotlin.collections and, in particular, the wealth of extension methods that exist.


KoanFunctionsWhat it does?C# EquivalentNotes
Filter and MapMap & FilterMap is a projection—it allows you to take in a collection of items and change each one. It is useful for selecting properties of objects in a collection. Filter lets you filter a collectionMap is the same as select and filter is the same as where
All Any And Other Predicatesany, all, count, and firstOrNullAny returns true if it finds any match to the provided expression. All requires all items in the collection to match the provided expression. Count provides the size of the collection. firstOrNull returns the first item in a collection which matches the expression or, if nothing does, it returns nullany, all, count, and firstOrDefaultAny, all, and count work the same as in .NET. Count should be avoided when size exists, since Count could cause it to be an O(n) operation to determine the size, though it depends on the collection implementation. firstOrNull is similar to .NET’s firstOrDefault except that it returns null if there is no match, whereas .NET might return null (only for reference types, like classes) and defaults for value types (0 for int, false for boolean, etc.).
FlatmapflatMapWhere map returns a collection that has the same size as the input, however flatMap the resulting collection can be a different size from the inputselectMany
Max and minmax and maxBymaxBy returns the largest value in the collection by letting you select which property to use for the orderingMaxInteresting that .NET uses one function name to do what Kotlin does with max and maxBy.
sortsortBysortBy lets you sort the collection with an O(n2) performanceorderBy
SumsumBysum
GroupBygroupByReturns a map (or dictionary) where the key is one provided by the expression and the value is the items from the input collection that match the expressionGroupBy
PartitionpartitionPartition returns a Pair with a list in both values, and the expression defines what goes into each value. Basically, you are splitting a collectionNo direct option for this. You could use take if you only cared about half the collection.
FoldfoldAllows you to produce a single value from a collection; normally aggregation—for example, adding up all values in an arrayAggregate

Going through these exercises was really interesting, and I'm glad there is a lot of similar functionality to .NET’s LINQ functions.