Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scala: flatMap with tuples

Tags:

scala

flatmap

Why is the below statement valid for .map() but not for .flatMap()?

 val tupled = input.map(x => (x*2, x*3))

 //Compilation error: cannot resolve reference flatMap with such signature
 val tupled = input.flatMap(x => (x*2, x*3))

This statement has no problem, though:

val tupled = input.flatMap(x => List(x*2, x*3))
like image 988
Somasundaram Sekar Avatar asked Jan 05 '23 13:01

Somasundaram Sekar


1 Answers

Assuming input if of type List[Int], map takes a function from Int to A, whereas flatMap takes a function from Int to List[A].

Depending on your use case you can choose either one or the other, but they're definitely not interchangeable.

For instance, if you are merely transforming the elements of a List you typically want to use map:

List(1, 2, 3).map(x => x * 2) // List(2, 4, 6)

but you want to change the structure of the List and - for example - "explode" each element into another list then flattening them, flatMap is your friend:

List(1, 2, 3).flatMap(x => List.fill(x)(x)) // List(1, 2, 2, 3, 3, 3)

Using map you would have had List(List(1), List(2, 2), List(3, 3, 3)) instead.

like image 116
Gabriele Petronella Avatar answered Jan 11 '23 02:01

Gabriele Petronella