Main navigation

Learning Kotlin: Collections

This is the 15th post in a multipart series.
If you want to read more, see our series index

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 reasons we are not breaking this down as we did before is because the common theme here is working the kotlin.collections and in particular the wealth of extension methods that exist.

Any returns true if it finds one 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 null

Any, all and count work the same as in .NET. Count should be avoided when size exists, since Count could cause it to be on O(n) operation to determine the sized, though it depends on the collection implementation. firstOrNull is similar to .NETs firstOrDefault except, it returns null if there is no match where .NET might return null (only for reference types, like classes) and what the default is for value types (0 for int, false for boolean etc...)