user610 user610 - 1 year ago 42
Scala Question

Storing values obtained from for each loop Scala

Scala beginner who is trying to store values obtains in a Scala foreach loop but failing miserably.
The basic foreach loop looks like this currently:

order.orderList.foreach((x: OrderRef) => {
val references = x.ref}))


When run this foreach loop will execute twice and return a reference each time. I'm trying to capture the reference value it returns on each run (so two references in either a list or array form so I can access these values later)

I'm really confused about how to go about doing this...

I attempted to retrieve and store the values as an array but when ran, the array list doesn't seem to hold any values.

This was my attempt:

val newArray = Array(order.orderList.foreach((x: OrderRef) => {
val references = x.ref
}))
println(newArray)


Any advice would be much appreciated. If there is a better way to achieve this, please share. Thanks

Answer Source

Use map instead of foreach

order.orderList.map((x: OrderRef) => {x.ref}))

Also val references = x.ref doesn't return anything. It create new local variable and assign value to it.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download