Map, map and FlatMap in Scala

Source: Internet
Author: User

One of the things I like on the Scala is it ' s collections framework. As a non CS graduate I only very lightly covered functional programming at university and I ' d never come across it until S Cala. One of the benefits of Scala is, the functional programming concepts can be introduced slowly to the programmer. One of the first places you'll start to use functional constructs are with the collections framework.

Chances is your first collection is a list of items and we might want to apply a function to each item in the list I n some.

Map works by applying a function to each element in the list.

scala> val L = list (1,2,3,4,5)

scala> l.map (x = x*2)
Res60:list[int] = List (2, 4, 6, 8, 10)

So there is some occasions where you want to return a sequence or list from the function, for example an Option

Scala> def f (x:int) = if (x > 2) Some (x) Else None

scala> l.map (x = f (x))
Res63:list[option[int]] = List (None, None, Some (3), Some (4), Some (5))

FLATMAP works applying a function that returns a sequence for each element in the list, and flattening the results into th E original list. This was easier to show than to explain:

Scala> def g (v:int) = List (V

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.