A collection of Scala flatMap examples | Scala collections | flatMap method | alvinalexander.com

Sure. When I was first trying to learn Scala, and cram the collections' flatMap method into my brain, I scoured books and the internet for great flatMap examples. Once I had a little grasp of it I started creating my own examples, and tried to keep them simple. To get started, the following examples show the differences between map and flatMap on a sequence of String: Quite a difference, right? Because flatMap treats a String as a sequence of Char, it flattens the resulting list of strings into a sequence of characters (Seq[Char]). flatMap is a combination of map and flatten, so it first runs map on the sequence, then runs flatten, giving the result shown. The following examples show more differences between map and flatMap for a simple String to Int conversion example. Given this toInt method: Here are a few examples to show how map and flatMap work on a simple list of strings that you want to convert to Int: The following code is not mine (see the URL below), but it does a great job of demonstrating flatMap when given the simple method g, where g returns three Int values when given one Int as input. That is, it transforms the single Int to the three resulting Ints: Here's an interesting use of flatMap I just thought about. Although there are other ways to get the values from a Scala map, you can use flatMap for this purpose: If you're new to Scala, note that the flatMap example is the same as this line of code, which may be more understandable: The folks at Twitter have put out some excellent Scala documentation, including a collection of flatMap examples that I've found in two different documents. They also show the following example of flatMap with Option. Remember that an Option is a container of 0 or 1 things, then guess what this code does: This morning (Nov. 2, 2012), I saw the following additional flatMap examples in a new presentation by Marius: That example comes from this page. If you look at that page, you’ll see that the other examples use map, but this particular example uses flatMap. It’s an interesting exercise to look at those examples and wonder why this is. I hope it helps to show some Scala flatMap examples, without too much discussion for the moment. In the end, flatMap is just a combination of map and flatten, so if map leaves you with a list of lists (or strings), add flatten to it. If that gives you what you need, call flatMap instead of map and flatten. After a while your brain will naturally think 'flat map' without needing those intermediate steps. If you have any flatMap examples you want to share, or improvements to the code shown, just leave a note in the Comments section. Source.


Яндекс.Метрика Рейтинг@Mail.ru Free Web Counter
page counter
Last Modified: April 18, 2016 @ 11:11 pm