score:7

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

score:7

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:

indices.map(index => A.apply(index))

You can leave off apply:

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

You can also use the underscore syntax:

indices.map(A(_))

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

indices.map(A)

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)
indices map A foreach println

Related Query

More Query from same tag