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 |