Reputation: 64207
val inArray = Array("a", "b", "c", "d")
// ...
val outArray = Array("a1", "a2", "a3", "b1", "b2", "b3", "c1", "c2", "c3", "d1", "d2", "d3")
How to map inArray
to outArray
?
The idea is to iterate through inArray
yielding 3 elements (by concatenating an index in this example) from each of its elements.
Upvotes: 7
Views: 2750
Reputation: 134260
This can look better using a for-comprehension
for {
s <- inArray
i <- Array(1, 2, 3) //or other traversable
}
yield s + i
This uses a combination of map and flatMap under the covers as described in detail in the SLS
Upvotes: 7
Reputation: 42037
You can do that with flatMap
.
inArray.flatMap(c => (1 to 3).map(c+))
Upvotes: 13
Reputation: 92016
Using for
-comprehension.
scala> for {
| x <- Array("a", "b", "c", "d")
| n <- 1 to 3
| } yield x + n
res0: Array[java.lang.String] = Array(a1, a2, a3, b1, b2, b3, c1, c2, c3, d1, d2, d3)
Upvotes: 5