Accepted answer

The most concise way I can think of is to flip your mental model and put indices first:

indices map A

And, I would potentially suggest using lift to return an Option

indices map A.lift


You can use map on indices, which maps each element to a new element based on a mapping lambda. Note that on Array, you get an element at an index with the apply method: => A.apply(index))

You can leave off apply: => A(index))

You can also use the underscore syntax:

When you're in a situation like this, you can even leave off the underscore:

And you can use the alternate space syntax:

indices map A

You were trying to use foreach, which returns Unit, and is only used for side effects. For example:

indices.foreach(index => println(A(index)))
indices map A foreach println

Related Query

More Query from same tag