Data operations in a collection

Kotlin provides out-of-the-box support for its collection framework. As a result, the collections framework in Kotlin is full of interesting features that make it stand apart from the collections framework in other languages, such as Java. You already got introduced with some of those features, such as separate interfaces for read-only and mutable collections, square box operator-like arrays, and so on. What I'm going to introduce now is probably the most interesting feature of Kotlin's collections framework, but goes mostly unnoticed—data operation functions.

Kotlin supports data operation functions for all of its collections framework interfaces, objects, and classes. By data operation functions, I mean the operators and functions by which we can access, process or operate on data from a collection; if you are familiar with ReactiveX framework/RxJava/RxKotlin, you'll find it similar as Kotlin picked them mostly from there.

The following is a list of a few of the collection data operation functions that we are going to cover here:

  • The map function
  • The filter function
  • The flatMap function
  • The drop functions
  • The take functions
  • The zip functions

So, what are we waiting for? Let us get started.

Though, the data operation functions with collections make you feel like you're working with streams/Rx, they are in no way similar to streams/Rx. What they do is simply use high order functions and extension functions to provide you with stream-like interfaces and internally they operate on the same loops (yes, you read it right, they use loops to produce results and then return it from the function just like a simple imperial program). It is advisable to avoid bigger chains of these functions in your program, as you'll end up with multiple loops. Using forEach or your own loop in such scenarios is a better choice, as you will be able to perform multiple operations with a single loop with forEach or with your own loop. However, for a single operation or small chains, you can definitely use these functions to make your code well organized.
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.116.67.70