简体   繁体   中英

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

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.

Agree with answer 1, and I believe the reason is below:

Return of 'foreach' or 'for' should be 'Unit', and 'map' is an with an changed type result like example below:

def map[B](f: (A) ⇒ B): Array[B]

Compare To for and foreach , the prototype should be like this

def foreach(f: (A) ⇒ Unit): Unit

So If you wanna to get an changed data which is maped from your source data, considering more about functions like map , flatMap , and these functions will traverse all datas like for and foreach (except with yield ), but with return values.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM