Somasundaram Sekar Somasundaram Sekar - 1 year ago 446
Scala Question

Scala: flatMap with tuples

Why is the below statement valid for map but not for flatMap

val tupled = => (x*2, x*3))

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

EDIT: Below has no problem though

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

Answer Source

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

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download