Scala Collections - Flatten Method


Advertisements

flatten() method is a member GenericTraversableTemplate trait, it returns a single collection of elements by merging child collections.

Syntax

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.

Usage

Below is an example program of showing how to use flatten method −

Example

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.

Command

\>scalac Demo.scala
\>scala Demo

Output

List(1, 2, 3, 4)
Advertisements