5

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].

3 Answers 3

13

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

Sign up to request clarification or add additional context in comments.

Comments

7

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

1 Comment

And even more concise input.flatMap(_.toList)
4

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.

1 Comment

Actually all you need is type ascription: val input:Array[Array[Int]] = ...

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.