Описание слайда:
flatMap
flatten “flattens” a list (removes one level of nesting)
scala> val nested = List(List(1, 2, 3), List(4, 5))
nested: List[List[Int]] = List(List(1, 2, 3), List(4, 5))
scala> nested flatten
res0: List[Int] = List(1, 2, 3, 4, 5)
flatMap is like map, but the function given to flatMap is expected to return a list of values; the resultant list of lists is then “flattened”
Syntax:
def map[B](f: (A) => B): List[B]
def flatMap[B](f: (A) => Traversable[B]): List[B]
Example:
scala> val greeting = List("Hello".toList, "from".toList, "Scala".toList)
greeting: List[List[Char]] = List(List(H, e, l, l, o), List(f, r, o, m), List(S, c, a, l, a))
scala> greeting map (word => word.toList)
res2: List[List[Char]] = List(List(H, e, l, l, o), List(f, r, o, m), List(S, c, a, l, a))
scala> greeting flatMap (word => word.toList)
res3: List[Char] = List(H, e, l, l, o, f, r, o, m, S, c, a, l, a)