lserlohn
lserlohn

Reputation: 6206

How does one flatten an array of arrays in Scala?

I have the following array:

val input = Array(Array(), Array(22,33), Array(), Array(77), Array(88,99))

It contains empty arrays. I want to get a flattened array without any empty arrays, so the output should be:

Array(22,33,77,88,99)

I tried the flatten function, but it seems to not work with the type of Array[_ <: Int].

Upvotes: 5

Views: 8868

Answers (3)

Jordan Cutler
Jordan Cutler

Reputation: 582

Another way of writing:

input.flatMap(_.toList)

The empty arrays get converted to Nils and since it's a flatMap the Nils get flattened out

Upvotes: 13

Euge
Euge

Reputation: 749

Monads are your friends:

for { a <- input; b <- a.toList } yield b

Edit: If you specify the type, flatten works fine

val input: Array[Array[Int]] = Array(Array(), Array(22,33), Array(), Array(77), Array(88,99))
input.flatten

Upvotes: 7

Alvaro Carrasco
Alvaro Carrasco

Reputation: 6172

It's inferring Array[_ <: Int] because some of the arrays are empty. Try this:

val input = Array(Array[Int](), Array(22,33), Array[Int](), Array(77), Array(88,99)).flatten

That ensures that the resulting type is Array[Array[Int]] which should be flattenable.

Upvotes: 4

Related Questions