flatten() method is a member GenericTraversableTemplate trait, it returns a single collection of elements by merging child collections.
The following is the syntax of flatten method.
def flatten[B]: Traversable[B]
Here, f: (A) ? GenTraversableOnce[B] is a predicate or condition to be applied on each element of the collection. This method returns the Option element containing the matched element of iterator which satisfiles the given condition.
Below is an example program of showing how to use flatten method −
object Demo { def main(args: Array[String]) = { val list = List(List(1,2), List(3,4)) //apply operation val result = list.flatten //print result println(result) } }
Save the above program in Demo.scala. The following commands are used to compile and execute this program.
\>scalac Demo.scala \>scala Demo
List(1, 2, 3, 4)